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
Kernel.system("cat #{params[:filename]}")Secure Code
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."
endRemediation
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
| Field | Value |
|---|---|
| ID | CODE-0539 |
| Category | Injection |
| Severity | CRITICAL |
| CWE | CWE-78 |
| Confidence | HIGH |
| Impact | HIGH |
| Likelihood | HIGH |
| Exploitability | EASY |
| Tags | os-command-injection, shell-injection |
| OWASP | A1:2017-Injection, A03:2021-Injection |