Updated 3 days ago | GitHub
On this page

Remote Code Execution

Remote Code Execution is when external code is able to execute internal, operating-system-level commands on a server from a distance.

Once an attacker has access to the internal OS-level, it is possible to perform any task a logged in user could do.

  • Read, add, modify, delete files
  • Change access privileges, passwords
  • Turn on and off configurations and services
  • Communicate to other servers

This is the most potent attack, but it is not easy to perform. This is because there is a divide between the operating system and the software running on it. There is no casual access between them, but that does not mean there are no access pathways. Most programming languages have functions which allow them to communicate directly with the underlying OS.

In order to pull off Remote Code Execution, two things are required:

  • A programmer must use a function which allows communication with the OS.
  • An attacker must be able to get dynamic data into that function call.

Common System Execution Functions

Every programming language has different names for these powerful OS-communication functions. But many of them borrow from a pool of common function names.

  • system, %x, exec, ``
  • shell, sh, shell_exec
  • open, popen, proc_open
  • call, subprocess, spawn
  • passthru, eval

This is not a complete list, but it does provide keywords that should send up red flags if you see them being used.


Here is an example in PHP where the system() function is being used to ask the OS for a list of files in a directory.

<?php
  // list_images.php
  $dir = $_GET['dir'];
  // list files in a subdirectory of images
  $cmd = 'ls images/' . $dir;
  // system() prints the command's output directly; the second arg
  // captures the integer exit status (0 on success), not the text output.
  system($cmd, $return_code);

  // GET: /list_images.php?dir=Vacation
  // GET: /list_images.php?dir=Vacation%3Bcat%20%2Fetc%2Fpasswd
?>

(%3B is a semicolon; %2F is a slash; %20 is a space)

It might seem that the dynamic value of dir will be limited to listing files in the images/ directory. But the injection is able to end that command and issue a second command which lists out the contents of the system’s user account file (/etc/passwd). On modern Linux this leaks usernames, UIDs, home directories, and login shells; hashed passwords are stored separately in /etc/shadow, but the account inventory it exposes is still valuable reconnaissance.


File paths

Key OS-communication functions such as system() are not the only functions which have OS access. Any function or language construct which accesses the system’s files is potentially vulnerable. Use caution whenever file paths are referenced. In PHP, the most commonly used are include, include_once, require, and require_once, which are language constructs rather than functions. But there are many functions which open, read, or save information to files.

In the case of include/require, dynamic data can be used to change which file is loaded.

Example

<?php
  // products.php
  $info_file = $_GET['category'] . '_info.php';
  include($info_file);

  // GET: /products.php?category=hats
  // GET: /products.php?category=..%2Fprivate%2Fdb_credentials
?>

(%2F is a slash)

The malicious second request resolves to include('../private/db_credentials_info.php'), telling the file system to go up one directory (..) and load the private database credentials file (assuming an attacker has guessed or discovered the suffixed filename). Historically attackers used a null byte (%00) to truncate the appended _info.php suffix; that trick was fixed in PHP 5.3.4 and no longer works on supported PHP versions.


Remote Code Execution Preventions

The best prevention is to avoid using system functions. This is generally true, but especially when working with dynamic data. Usually there is a better, safer way to do the same thing. In some programming languages (including PHP) it is possible to disable these functions entirely so that they cannot be used.

If it is unavoidable to use system functions and for more common language constructs like include/require, use extreme caution and plan for Defense in Depth.

  • Whitelist actions
  • Sanitize and validate input
  • Validate returned data

Applied to the list_images.php example above, the OWASP OS Command Injection Defense Cheat Sheet gives these defenses, in order of preference:

  1. Avoid the OS command. Listing a directory does not need a shell. PHP’s scandir() returns the directory’s entries as an array (or false on failure), so no command string is ever built. Combine it with allowlist validation so that dir can only be one plain directory name. The pattern below rejects semicolons, spaces, slashes and dots, which blocks both the command injection and ../ path traversal.
<?php
  // list_images.php (safer version)
  $dir = $_GET['dir'] ?? '';
  // allowlist: 1-64 letters, digits, underscores, or hyphens
  // (the D modifier stops $ from also matching before a trailing newline)
  if (!is_string($dir) || preg_match('/^[A-Za-z0-9_-]{1,64}$/D', $dir) !== 1) {
    http_response_code(400);
    exit('Invalid directory name');
  }
  $files = scandir('images/' . $dir);
  if ($files === false) {
    http_response_code(404);
    exit('Directory not found');
  }
  // scandir() includes the . and .. entries; leave them out
  foreach (array_diff($files, ['.', '..']) as $file) {
    echo htmlspecialchars($file), "<br>\n";
  }
?>
  1. If a shell command is unavoidable, escape every argument with escapeshellarg(). On Unix-like systems it wraps the value in single quotes and escapes any single quotes inside it, so the shell treats the value as one argument. Use it instead of escapeshellcmd(). That function only ensures that the intended command runs, and an attacker can still add extra arguments to it. Escaping does not replace validation. OWASP notes that an attacker can still pass a single argument, and a value that starts with - may be read as an option. Keep the allowlist check from option 1, and where the command supports it, put -- before user-supplied arguments to end option parsing.
  // after the same allowlist check as above
  system('ls -- ' . escapeshellarg('images/' . $dir), $return_code);
  1. Keep the command and its data separate. Hardcode the executable and its options, and never let the user choose which program runs. As of PHP 7.4, proc_open() accepts the command as an array of arguments. The process then starts directly, without going through a shell, and PHP handles the argument escaping. Validate the arguments against an allowlist here too.

Third-party software

Even if a developer’s code is free of all system-calling functions, it does not mean that the system has none. Code by third-parties such as applications, libraries, and plug-ins could be using RCE-vulnerable functions.

One well-known example is ImageMagick. ImageMagick is a popular image processing library used by thousands of websites. Unfortunately, it had a Remote Code Execution vulnerability, dubbed ImageTragick (CVE-2016-3714).

This is a good reason to reduce code dependencies on third-party software (Simple is More Secure). Only use reputable third-party software or open source software where the code can be reviewed.

Even the best third-party developers make mistakes and have to issue security bug fixes. Regularly check to ensure that all software versions are up to date.