What is Command Injection?
Command injection is a cyber attack that involves executing arbitrary commands on a host operating system (OS). Typically, the threat actor injects the commands by exploiting an application vulnerability, such as insufficient input validation.
For example, a threat actor can use insecure transmissions of user data, such as cookies and forms, to inject a command into the system shell on a web server. The attacker can then leverage the privileges of the vulnerable application to compromise the server.
Command injection takes various forms, including direct execution of shell commands, injecting malicious files into a server’s runtime environment, and exploiting vulnerabilities in configuration files, such as XML external entities (XXE).
Code Injection vs. Command Injection
Code injection is a generic term for any type of attack that involves an injection of code interpreted/executed by an application. This type of attack takes advantage of mishandling of untrusted data inputs. It is made possible by a lack of proper input/output data validation.
A key limitation of code injection attacks is that they are confined to the application or system they target. If an attacker can inject PHP code into an application and execute it, malicious code will be limited by PHP functionality and permissions granted to PHP on the host machine.
Command injection typically involves executing commands in a system shell or other parts of the environment. The attacker extends the default functionality of a vulnerable application, causing it to pass commands to the system shell, without needing to inject malicious code. In many cases, command injection gives the attacker greater control over the target system.
Command Injection Vulnerability Examples
Here are three examples of how an application vulnerability can lead to command injection attacks. These examples are based on code provided by OWASP.
Example 1: File Name as Command Argument
Here is an example of a program that allows remote users to view the contents of a file, without being able to modify or delete it. The program runs with root privileges:
int main(char* argc, char** argv) { char cmd[CMD_MAX] = "/usr/bin/cat "; strcat(cmd, argv[1]); system(cmd); }
Although the program is supposedly innocuous—it only enables read-only access to files—it enables a command injection attack. If the attacker passes, instead of a file name, a string like:
“;rm -rf /”
The call to system() will fail to execute, and then the operating system will perform recursive deletion of the root disk partition.
Example 2: Manipulating APPHOME Environment Variable
The following code snippet determines the installation directory of a certain application using the $APPHOME environment variable and runs a script in that directory.
... char* home=getenv("APPHOME"); char* cmd=(char*)malloc(strlen(home)+strlen(INITCMD)); if (cmd) { strcpy(cmd,home); strcat(cmd,INITCMD); execl(cmd, NULL); } …
The problem is that the code does not validate the contents of the initialization script. If the attacker manages to modify the $APPHOME variable to a different path, with a malicious version of the script, this code will run the malicious script. This constitutes a command injection attack.
Example 3: Manipulating $PATH Variable
The following code may be used in a program that changes passwords on a server, and runs with root permissions:
system("cd /var/yp && make &> /dev/null");
The problematic part of this code is the use of make. While the attacker cannot change the code itself, because it does not accept user inputs, they can modify the $PATH variable. This can cause the command to execute in a different path controlled by the attacker. In that other folder path, the attacker can plant a malicious version of the make binary.
Because the parent program has root privileges, the malicious version of make will now run with root privileges.
The bottom line of all three examples is that any command that invokes system-level functions like system() and exec() can lend their root privileges to other programs or commands that run within them.
Command Injection Methods
Here are some of the vulnerabilities that commonly lead to a command injection attack.
Arbitrary command injection
Some applications may enable users to run arbitrary commands, and run these commands as is to the underlying host.
Arbitrary file uploads
If an application allows users to upload files with arbitrary file extensions, these files could include malicious commands. On most web servers, placing such files in the webroot will result in command injection.
Insecure serialization
Server-side code is typically used to deserialize user inputs. If deserialization is performed without proper verification, it can result in command injection.
Server-side template injection (SSTI)
Many web applications use server-side templates to generate dynamic HTML responses. This makes it possible for attackers to insert malicious server-side templates. SSTI occurs when user input is embedded in a template in an insecure manner, and code is executed remotely on the server.
XML external entity injection (XXE)
XXE occurs in applications that use a poorly-configured XML parser to parse user-controlled XML input. This vulnerability can cause exposure of sensitive data, server-side request forgery (SSRF), or denial of service attacks.
Command Injection Prevention
Here are several practices you can implement in order to prevent command injections:
- Avoid system calls and user input—to prevent threat actors from inserting characters into the OS command.
- Set up input validation—to prevent attacks like XSS and SQL Injection.
- Create a white list—of possible inputs, to ensure the system accepts only pre-approved inputs.
- Use only secure APIs—when executing system commands such as execFile()
- Use execFile() securely—prevent users from gaining control over the name of the program. You should also map user input to command arguments in a way that ensures user input does not pass as-is into program execution.
Command Injection Protection with Imperva
Imperva protects against command injection and many other attacks using its market-leading web application firewall (WAF). Imperva WAF, offered both in the cloud and as an on-premise Gateway WAF solution, permits legitimate traffic and prevents bad traffic, safeguarding applications both inside your network and at the edge.
In addition to protecting against command injection, Imperva provides multi-layered protection to make sure websites and applications are available, easily accessible and safe. The Imperva application security solution includes:
- DDoS Protection—maintain uptime in all situations. Prevent any type of DDoS attack, of any size, from preventing access to your website and network infrastructure.
- CDN—enhance website performance and reduce bandwidth costs with a CDN designed for developers. Cache static resources at the edge while accelerating APIs and dynamic websites.
- Bot management—analyzes your bot traffic to pinpoint anomalies, identifies bad bot behavior and validates it via challenge mechanisms that do not impact user traffic.
- API security—protects APIs by ensuring only desired traffic can access your API endpoint, as well as detecting and blocking exploits of vulnerabilities.
- Account takeover protection—uses an intent-based detection process to identify and defends against attempts to take over users’ accounts for malicious purposes.
- RASP—keep your applications safe from within against known and zero‑day attacks. Fast and accurate protection with no signature or learning mode.
- Attack analytics—mitigate and respond to real security threats efficiently and accurately with actionable intelligence across all your layers of defense.