DEV Community

Supratip Banerjee
Supratip Banerjee

Posted on

Introduction to CWE 78—OS Command Injection in Java Security

Image description

Photo by Christopher Gower on Unsplash

Introduction

A command injection vulnerability is a type of critical application vulnerability that involves dynamically produced content. Attackers use a susceptible application to execute arbitrary instructions on the host operating system. They provide malicious data to the system shell to acquire control of a website and perform any action or process that the underlying program supports.

Attackers who access these systems can change, manipulate, or read data, insert commands that steal data or attack infrastructure, and engage in other harmful actions. The insertion of commands is heavily reliant on privileges.

OS Command Vulnerability

How It Works

** First, the attacker finds a critical vulnerability in an application. This enables them to inject malicious code into the operating system and get access to any feature provided by the underlying program.
** Using HTML code, the attacker modifies dynamically produced content on a web page via an input method such as a form field or cookies.
** After inserting the code into the impacted web page, browsers interpret the code. This enables the attacker to execute particular instructions across user computers, user networks, and the network of the infected machine.

Image description
Source

The Attack's Anatomy

The attack script can use the system call "nslookup [hostname]" to perform nslookup with the HOSTNAME as an argument from the user. If the application fails to remove separators from the externally produced HOSTNAME parameter, the attacker can insert separators into the argument and execute their own instructions.

An application uses input to choose which software to execute and which instructions to include in the assault. The program sanitizes the input before redirecting it to the operating system.

Let’s say the program is reliant on exec [COMMAND]. The input comes from a different source. Once an attacker has control of the [COMMAND] parameter, they can run any command or script they want on the machine.

Sample Vulnerable Code

Scenario 1

The following example reads the name of a shell script to run:

String script = System.getProperty("SCRIPTNAME");
if (script != null)
    System.exec(script);
Enter fullscreen mode Exit fullscreen mode

If an attacker gains access to this attribute, they can change it to point to a malicious application.

Scenario 2

The following example uses a technique to convert geographic coordinates from latitude and longitude to UTM format.
The technique provides the latitude and longitude coordinates to the external application as a command-line parameter. It performs some processing to obtain the results of the transformation and return the resultant UTM coordinates.

public String coordinateTransformLatLonToUTM(String coordinates)
{
  String utmCoords = null;
  try {
    String latlonCoords = coordinates;
    Runtime rt = Runtime.getRuntime();
    Process exec = rt.exec("cmd.exe /C latlon2utm.exe -" + latlonCoords);
   // process results of coordinate transform

   // …
  }
  catch(Exception e) {...}
    return utmCoords;
  }
Enter fullscreen mode Exit fullscreen mode

The technique, however, does not ensure that the coordinate input argument has appropriately formatted latitude and longitude data. A malicious user may run another program locally to the application server by adding '&' followed by the command for another program to the end of the coordinate string if the input coordinates have not been verified before calling this function. The '&' command tells the Windows operating system to run another program.

Impact

The consequences of command injection attacks include data loss and integrity and unauthorized remote access to the machine that hosts the susceptible application.

Unlike other injection attacks based on specific languages, command injection attacks can occur in any operating system and impact any programming language that may invoke OS commands.

An attacker may modify or damage a database, steal customer records, utilize an API to initiate a specific process or event, or conduct a DDoS assault. Once an attacker has obtained control of a server, they can use the underlying program to exploit any software capability.

Prevention

After determining that an OS command injection attack has occurred, it is important to disable access to the affected application. This may necessitate a short-term remedy: modifying the web server's native capabilities or changing the system access rights to the relevant file.

Remediation and WhiteSource Cure

Addressing possible vulnerabilities that might lead to an OS command injection attack is critical. There are a few options for completing the task:

The first is keeping manipulation at bay at the source. Any programs accessed via a web browser mustn’t contain user-controllable data in operating system instructions. Development and cybersecurity teams should prioritize deploying code that prevents unwanted instructions from causing server-level processes to be manipulated.

The second is rejecting unacceptable code. It’s better to rigorously verify all user data if a more secure solution to execute server-level activities is not found. This is accomplished by developing a whitelist of permissible values. Furthermore, some companies restrict input to short alphanumeric characters. The system immediately rejects any input that falls outside of the permitted data range.

WhiteSource Cure

Many organisations are transferring application security-related duties onto developers. This is done with the aim to reduce the amount of vulnerabilities that need to be addressed just before an application is launched.

Image description

WhiteSource Cure is a free, easy-to-use, auto-remediation tool designed for custom code. This next-generation technique helps businesses accelerate the delivery of secure software at scale. It has faster cleanup options, and is free for developers.

Cure is particularly handy as it automatically generates executable repair reports after each scan. These reports target OS Command flaws discovered in your code and provide fix recommendations that work for your specific code. It’s as if they were created by you! Its suggestions are case-specific, accurate, and easy to implement, saving you time and promoting secure programming.

Image description

Source

Remediating OS Command Injection Using WhiteSource Cure

WhiteSource Cure identifies the appropriate user-given input to be sanitized using static code insights from the detected file.
OS Command Injection
Vulnerable Code 1

User data is gathered via program parameters and then utilized to build an OS command.

public class commandInjection {
       public static void main(String[] args) throws InterruptedException, IOException {
             String dir = args[0];
             Runtime rt = Runtime.getRuntime();             
             Process proc = rt.exec("cmd.exe /C dir " + dir);
             int result = proc.waitFor();
             if (result != 0) {
                    System.out.println("process error: " + result);
             }
             InputStream in = (result == 0) ? proc.getInputStream() :
                    proc.getErrorStream();
             int c;
             while ((c = in.read()) != -1) {
                    System.out.print((char) c);
             }
       }
}
Enter fullscreen mode Exit fullscreen mode

It's simple to anticipate the outcome of executing this program with the following arguments:

"c:\tmp > dir.txt & type c:\Windows\system.ini"
Enter fullscreen mode Exit fullscreen mode

In this example, the software will show the system.ini configuration file. The significant part is that the attacker has complete control over what happens in the targeted system.
Remediation

The weakness can be fixed by comparing user data to a whitelist of just permitted characters (or command list).

if (Pattern.matches("[0-9A-Za-z@.]+", dir)) {
    Process proc = rt.exec("cmd.exe /C dir " + dir);
}
Enter fullscreen mode Exit fullscreen mode
Vulnerable Code 2

The basic line of defense is to avoid directly invoking OS instructions. Built-in library functions are an excellent alternative to OS Commands—they cannot be modified to accomplish tasks other than those for which they were designed.

system("mkdir /dir_name")
Enter fullscreen mode Exit fullscreen mode
Remediated code:
mkdir()
Enter fullscreen mode Exit fullscreen mode

This is the preferable option if libraries or APIs for the language you use are available.

Vulnerable Code 3

In this example, the command and its parameters are provided as a single string, making it simple to modify and insert malicious text.

ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");
Enter fullscreen mode Exit fullscreen mode
Remediated code:

Here's an instance of how to start a process with a changed working directory. Each argument and the command are provided separately. This makes validating each word simple and eliminates the possibility of malicious strings being added.

ProcessBuilder pb = new ProcessBuilder("TrustedCmd", "TrustedArg1", "TrustedArg2");
Map<String, String> env = pb.environment();
pb.directory(new File("TrustedDir"));
Process p = pb.start();
Enter fullscreen mode Exit fullscreen mode

Validate the canonical path of a file based on user input. If the canonical and absolute paths match, then the code should proceed.

Conclusion

The most effective approach to avoid OS command injection vulnerabilities is to never use application-layer code to call out to OS commands. In almost every situation, safer platform APIs can be used to achieve the needed functionality.

Thus, addressing these vulnerabilities is very important. An implement like Cure makes the process seamless, less error-prone, and comprehensive, which is always better.

Discussion (0)