Command Injection: Definition, Risks, and Prevention Tips

What is Command Injection?

Command injection is a type of vulnerability that occurs when an application executes system commands (also known as shell commands) in response to user input without proper validation or sanitization.

This vulnerability allows attackers to inject malicious commands into the input fields of the application, leading to unauthorized execution of arbitrary commands on the underlying operating system.

Here’s how command injection typically works:

How does a Command Injection Attack work?

The application takes user input, often through form fields, URL parameters, or any other input mechanism.

Instead of providing legitimate input, an attacker injects malicious commands into these input fields. These commands are designed to exploit vulnerabilities in the application.

The application processes the input without proper validation, concatenating it with a system command and executing it.

The injected command is executed with the privileges of the application, potentially allowing attackers to perform a variety of malicious actions, such as:

  • Reading or writing files on the server.
  • Executing system commands.
  • Modifying or deleting data in the application’s database.
  • Escalating privileges to gain control over the entire system.

Code Injection vs. Command Injection

Code injection and command injection are vulnerabilities that allow attackers to execute arbitrary code on a system. While there are similarities, significant differences set them apart:

Command Injection Code Injection
Definition Command injection involves injecting and executing arbitrary system commands through vulnerable input fields in an application. Code injection involves injecting and executing arbitrary code within the context of a programming language or application runtime environment.
Execution Command injection typically occurs within the context of shell commands. These commands are executed by the operating system’s shell (e.g., bash, PowerShell) and can perform various system-level operations. Code injection can occur in various runtime environments, including interpreted languages (e.g., PHP, Python), compiled languages (e.g., Java, C++), and web frameworks (e.g., ASP.NET, Ruby on Rails).
Examples; Injecting commands into a web application’s parameter that is then passed to a shell command without proper validation.

Exploiting a system command executed by a server-side script that dynamically constructs shell commands using user-supplied input.

Injecting PHP code into a vulnerable web application to execute server-side scripting commands.

Exploiting a deserialization vulnerability in a Java application to execute arbitrary Java code.

Impacts Command Injection can lead to data breaches, server compromise, or other forms of system manipulation. Code Injection can result in various consequences, such as data manipulation, privilege escalation, remote code execution, or complete system compromise.

 

Command Injection Vulnerabilities

Command injection vulnerabilities can arise from various weaknesses in web applications. Here are some common vulnerabilities that can lead to command injection:

Improper Input Validation

  • Failure to validate and sanitize user input properly is one of the primary causes of command injection vulnerabilities.
  • If an application fails to validate input from users, attackers can inject malicious commands into input fields, which are then executed by the application.
  • Lack of input validation can occur in various forms, including failing to check for special characters, not validating input length, or allowing unrestricted input.

Untrusted Data in System Commands

  • Applications that construct system commands using untrusted data without proper validation are vulnerable to command injection.
  • For example, concatenating user input directly into a system command without sanitization can allow attackers to inject malicious commands.

Shell Metacharacters and Command Separators

  • Applications that do not properly handle shell metacharacters and command separators in user input are vulnerable to command injection.
  • Characters like ;, &, |, and others are interpreted by the shell as command separators, allowing attackers to inject additional commands.

Insufficient Access Controls

  • Lack of proper access controls can lead to command injection vulnerabilities, especially if sensitive functionality or system commands are accessible to unauthenticated or unauthorized users.
  • Attackers may exploit unrestricted access to execute malicious commands.

Dynamic Construction of Command Strings

  • Applications that dynamically construct command strings using user-supplied input without proper validation are susceptible to command injection.

Unsafe File Operations

  • Command injection vulnerabilities can also arise from unsafe file operations, where applications accept file paths or filenames as input and perform operations without proper validation.
  • Attackers can manipulate filenames to execute arbitrary commands using file-related functions vulnerable to command injection.

Insecure APIs or Interfaces

  • APIs or interfaces that allow the execution of system commands without proper validation are potential sources of command injection vulnerabilities.

Deserialization Vulnerabilities

  • Insecure deserialization of user-supplied data can lead to command injection vulnerabilities, particularly in applications that deserialize objects containing executable code.
  • Attackers can manipulate serialized objects to inject and execute arbitrary commands during the deserialization process.

XXE (XML External Entity)

  • An ill-configured XML parser creates a vulnerability space where attackers can exploit the application by injecting malicious XML payloads.
  • Command injection vulnerabilities can arise when attackers inject specially crafted XML payloads containing references to external entities or other malicious constructs. Learn more about how to prevent XXE attacks, here.

Types of Command Injection

1. Result-based Command Injection

In result-based command injection, the output of the executed command is visible in the response of the application.

Attackers can directly observe the results of the injected command, determining whether the execution was successful or not.

Example:

Scenario: An application executes a shell command containing user-supplied product and store IDs and returns the raw output from the command in its response.

Vulnerable Parameter: The user-supplied product and store IDs.

Example Command: `whoami`

The command `whoami` displays the name of the current user. If the output of this command is reflected in the application’s response, it indicates a result-based command injection vulnerability.

Result-based Command Injection Example

2. Blind Command Injection

In blind command injection, the output of the executed command is not directly visible in the application’s response.

Attackers cannot directly observe the results of the injected command but may infer success or failure through various techniques.

There are two types of blind command injection:

  1. Time-based Technique (Blind)

This technique relies on time delays to indirectly determine the success or failure of the injected command.

Attackers inject commands that cause noticeable delays in the application’s response time, allowing them to infer execution success.

Example

Scenario: The application executes a shell command containing user-supplied details, but the output from the command is not returned in the response.

Vulnerable Parameter: Email address

Example Command: `ping -c 10 127.0.0.1`

The `ping` command with a specified count causes a delay in the application’s response. By observing the delay, attackers can infer whether the injected command was executed successfully.

Image 1: The screenshot displays a standard request and response

Time-based Technique (Blind) - example

Image 2: The screenshot shows exploitation of vulnerable email parameter through blind command injection

Time-based Technique (Blind) - exploitation example

  1. File-based Technique (Semi-blind)

This technique is used when attackers cannot directly view the results of the injected command, but they can write it to a file accessible by them.

Output redirection is often used to capture the output from the command into a file.

Example:

  1. Initial Exploitation

The online image gallery application allows users to view details of images by providing the image’s filename as a parameter.

The application runs a system command to fetch image details, but it doesn’t display the output from the command in the response.

The email address parameter is identified as vulnerable to command injection.

A writable folder, /var/www/images/, is available for storing files.

  1. Exploitation Process:

The attacker injects a command into the email address parameter to write sensitive data to a file accessible by them.

For example, the attacker injects the command ls > /var/www/images/output.txt, which redirects the output of the ls command (list files) to a file named output.txt in the writable folder.

File-based Technique (Semi-blind) - Initial Exploitation

  1. Capturing Request: When the user clicks on “View details” of an image, which triggers a request to the server.

File-based Technique (Semi-blind) - Capturing request

  • The server responds with the filename parameter specifying the image name.

File-based Technique (Semi-blind) - obtaining image details

  • The attacker intercepts the response and identifies the filename parameter.

They replace the original value of the filename parameter with the one containing the output of the injected command, i.e., output.txt.

File-based Technique (Semi-blind) - Replacing Parameter Value

This allows the attacker to store sensitive data, such as directory listings, in a location accessible to them.

The attacker can then access the output.txt file through the web application and retrieve the data, potentially revealing sensitive information or aiding further exploitation.

How to Detect Command Injection Vulnerability?

Detecting command injection vulnerabilities involves thorough testing and analysis of the application’s input validation mechanisms, as well as examining how user supplied data is handled and processed by the application.

Here are some methods and techniques to detect command injection vulnerabilities:

Manual Code Review

  • Review the application’s source code, paying particular attention to places where user input is accepted and processed.
  • Look for instances where user input is concatenated directly into system commands without proper validation or sanitization.

Static Analysis Tools

  • Utilize static code analysis tools designed to identify potential command injection vulnerabilities.
  • These tools can automatically scan the codebase for insecure coding practices and highlight areas where command injection may occur.

Dynamic Analysis

  • Perform dynamic testing by submitting various payloads containing special characters and command injection attempts.
  • Monitor the application’s behavior and responses to injected commands to identify potential vulnerabilities.

Input Validation Testing

  • Test input fields and parameters for proper validation and sanitization.
  • Attempt to inject special characters, such as semicolons (;), pipes (|), or backticks (`), to see if they are properly filtered or escaped.

Web Application Scanners

  • Employ web application security scanners that include command injection detection capabilities.
  • These scanners can automatically crawl the application, identify input fields, and test them for command injection vulnerabilities.

Third-Party Services

  • Utilize third-party services or penetration testing tools that specialize in identifying command injection vulnerabilities.
  • These services may offer comprehensive scanning and reporting capabilities to help identify and remediate vulnerabilities.

Tool for Exploiting Command Injection

Commix is a command injection exploitation tool designed to assist web developers, penetration testers, and security researchers in identifying vulnerabilities in web applications.

Written in Python, it supports Linux, Mac OS X, and Windows platforms (experimental). Commix is open-source and available as a plugin on penetration testing frameworks like PTF and PentestBox.

Exploiting Command Injection via Commix :

Image 1: Here the IP field is vulnerable to command injection.

command-injection

Image 2: python commix.py –url=”http://192.168.32.130/vulnerabilities/exec/” –cookie=”PHPSESSID=63pq1tou816hc3tncbkhhpdj40; security=low” –data=”ip=127.0.0.1&submit=submit” –os-cmd=”uname” –current-user –hostname –is-root –users –passwords –privileges –sys-info

Command Injection exploitation - python-commix

Image 3: As observed, commix gives us all the details from the hostname till the user privileges

Command Injection exploitation - commix -hostname

How to Prevent Command Injection Attacks?

Input Validation and Sanitization

  • Validate and sanitize all user-supplied input before using it in dynamic queries or commands.
  • Utilize whitelisting only to allow expected characters or patterns in input fields, rejecting anything else.
  • Escape or encode special characters that have a specific meaning in command interpreters (e.g., shell metacharacters).

Parameterized Queries and Prepared Statements

  • Use parameterized queries or prepared statements when interacting with databases to prevent SQL injection, which can sometimes lead to command injection.
  • Parameterized queries bind user input to query parameters, preventing the injection of additional commands.

Safe APIs and Libraries

  • Employ secure APIs and libraries for executing system commands or interacting with the operating system.
  • Avoid using functions like system() or exec() that execute commands with user-controlled input.

Least Privilege Principle

  • Limit the privileges of the user or service executing system commands to the minimum required for the task.
  • Employ dedicated service accounts with restricted permissions rather than executing commands with elevated privileges.

Enable OS-level Protections

  • Implement proper file system permissions to restrict access to sensitive directories and files.
  • Utilize security mechanisms such as SELinux or AppArmor to enforce mandatory access controls and restrict system calls.

Content Security Policy (CSP)

  • Implement CSP headers to restrict the sources from which scripts can be loaded and executed in web applications.
  • CSP can help mitigate attacks by preventing the execution of inline scripts or scripts loaded from untrusted sources.

Prevent Command Injection with AppTrana WAAP

AppTrana WAAP is a powerful solution designed to prevent command injection attacks and protect web applications from various cyber threats.

By effectively monitoring and filtering HTTP traffic, the platform identifies, and blocks known attack patterns, including command injection payloads.

Leveraging both core and custom rules ensures that requests containing suspicious or malicious input are either blocked or sanitized.

The core rules provide immediate protection against common attack vectors, while the custom-built rules are meticulously crafted to address specific threats relevant to the application. The platform stays ahead of emerging security risks, offering comprehensive visibility and zero false positives.

Indusface
Indusface

Indusface is a leading application security SaaS company that secures critical Web, Mobile, and API applications of 5000+ global customers using its award-winning fully managed platform that integrates web application scanner, web application firewall, DDoS & BOT Mitigation, CDN, and threat intelligence engine.