Command Injection
Example 1: Python
Vulnerable Code:
Reason for vulnerability: User input is directly used in the command, allowing command injection.
Fixed Code:
Reason for fix: Validate and sanitize user input before using it in the command.
Example 2: Java
Vulnerable Code:
Reason for vulnerability: User input is directly used in the command, allowing command injection.
Fixed Code:
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