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:
pythonCopyimport os
def run_command(command):
os.system(command)
def process_user_input(user_input):
run_command(f"echo {user_input} >> log.txt")
Reason for Vulnerability:
This code directly incorporates user input into a shell command, allowing injection of arbitrary commands.
Fixed Code:
pythonCopyimport subprocess
import shlex
def run_command(command, args):
subprocess.run([command] + args, check=True)
def process_user_input(user_input):
run_command("echo", [user_input, ">>", "log.txt"])
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:
javaCopyimport java.io.IOException;
public class PingUtility {
public static String ping(String host) throws IOException {
Process process = Runtime.getRuntime().exec("ping " + host);
// Read and return process output
}
}
Reason for Vulnerability:
This code directly incorporates user input into a shell command, allowing injection of arbitrary commands.
Fixed Code:
javaCopyimport java.io.IOException;
public class PingUtility {
public static String ping(String host) throws IOException {
if (!isValidHostname(host)) {
throw new IllegalArgumentException("Invalid hostname");
}
ProcessBuilder pb = new ProcessBuilder("ping", host);
Process process = pb.start();
// Read and return process output
}
private static boolean isValidHostname(String host) {
return host.matches("^[a-zA-Z0-9.-]+$");
}
}
Reason for Fix:
The fixed code validates the hostname and uses ProcessBuilder to safely construct the command.
Ruby Example
Vulnerable Code:
rubyCopydef execute_command(command)
`#{command}`
end
puts execute_command(ARGV[0])
Reason for Vulnerability:
This code directly executes user-provided input as a shell command, allowing arbitrary command execution.
Fixed Code:
rubyCopyrequire 'open3'
def execute_command(command, *args)
raise ArgumentError, "Invalid command" unless ['ls', 'cat', 'echo'].include?(command)
stdout, stderr, status = Open3.capture3(command, *args)
raise "Command failed: #{stderr}" unless status.success?
stdout
end
begin
puts execute_command(ARGV[0], *ARGV[1..-1])
rescue ArgumentError, RuntimeError => e
puts "Error: #{e.message}"
end
Reason for Fix:
The fixed code uses a whitelist of allowed commands and Open3.capture3 for safer command execution.
Last updated