Skip to content

OS Command Injection

Description

User input should never be used in constructing commands or command arguments to functions which execute OS related functionality. Using external input without validation in functions like `Kernel.system`, `exec`, or any operations that interact with the shell or file system (`cat`, `delete` etc.) poses a severe security risk. These patterns can lead to command injection vulnerabilities, where an attacker could execute arbitrary commands on the system the application is hosted on, leading to data breaches, unauthorized access, or worse.

Examples

Insecure Code

ruby
Kernel.system("cat #{params[:filename]}")

Secure Code

ruby
user_filename_key = params[:filename_key]
allowed_filenames = {
  'file1' => 'allowed_file_1.txt',
  'file2' => 'allowed_file_2.txt',
}
if allowed_filenames.has_key?(user_filename_key)
  safe_filename = allowed_filenames[user_filename_key]
  content = File.read(safe_filename)
else
  puts "Invalid filename."
end

Remediation

Validate and sanitize all user input before using it in any system or shell operation. Consider using safer alternatives for executing system commands that don't directly pass user input to the shell, such as parameterized APIs or functions that handle arguments safely.

Rule Details

FieldValue
IDCODE-0539
CategoryInjection
SeverityCRITICAL
CWECWE-78
ConfidenceHIGH
ImpactHIGH
LikelihoodHIGH
ExploitabilityEASY
Tagsos-command-injection, shell-injection
OWASPA1:2017-Injection, A03:2021-Injection

References