Command Injection

Example 1: Python

Vulnerable Code:

pythonCopy codeos.system("ls " + request.args.get('dir'))

Reason for vulnerability: User input is directly used in the command, allowing command injection.

Fixed Code:

pythonCopy codedir = request.args.get('dir')
if not is_valid_directory(dir):
    abort(400)
os.system("ls " + dir)

Reason for fix: Validate and sanitize user input before using it in the command.

Example 2: Java

Vulnerable Code:

javaCopy codeString dir = request.getParameter("dir");
Runtime.getRuntime().exec("ls " + dir);

Reason for vulnerability: User input is directly used in the command, allowing command injection.

Fixed Code:

javaCopy codeString dir = request.getParameter("dir");
if (!isValidDirectory(dir)) {
    throw new IllegalArgumentException("Invalid directory");
}
Runtime.getRuntime().exec("ls " + dir);

Reason for fix: Validate and sanitize user input before using it in the command.


Python Example

Vulnerable Code:

Reason for Vulnerability:

This code directly incorporates user input into a shell command, allowing injection of arbitrary commands.

Fixed Code:

Reason for Fix:

The fixed code uses subprocess.run with a list of arguments, which prevents shell injection. It also uses shlex.quote for extra safety when constructing commands.


Java Example

Vulnerable Code:

Reason for Vulnerability:

This code directly incorporates user input into a shell command, allowing injection of arbitrary commands.

Fixed Code:

Reason for Fix:

The fixed code validates the hostname and uses ProcessBuilder to safely construct the command.

Ruby Example

Vulnerable Code:

Reason for Vulnerability:

This code directly executes user-provided input as a shell command, allowing arbitrary command execution.

Fixed Code:

Reason for Fix:

The fixed code uses a whitelist of allowed commands and Open3.capture3 for safer command execution.

Last updated