OS Command Injection zafiyetlerinden korunmanın en etkili yolu, sistem komutlarını tamamen kullanmaktan kaçınmaktır. Ancak bu mümkün değilse, güçlü güvenlik önlemleri alınmalıdır.
1. Öncelikli Savunma - Sistem Komutlarını Kullanmayın:
Platform API'lerini Tercih Edin:
• File operations için filesystem API'leri
• Network operations için socket libraries
• System info için native platform calls
• Database operations için prepared statements
$filename = $_GET['file'];
exec("cat " . $filename, $output);
$filename = $_GET['file'];
$content = file_get_contents($filename);
2. Input Validation ve Sanitization:
function validateInput($input) {
if (!preg_match('/^[a-zA-Z0-9]+$/', $input)) {
throw new Exception('Invalid input');
}
return $input;
}
function validateNumeric($input) {
if (!is_numeric($input)) {
throw new Exception('Must be numeric');
}
return intval($input);
}
3. Command Parameterization:
function safeCommandExecution($userInput) {
$safeInput = validateInput($userInput);
$command = ['/usr/bin/grep', '-F', $safeInput, '/var/log/app.log'];
$process = proc_open($command, $descriptors, $pipes);
if (is_resource($process)) {
$output = stream_get_contents($pipes[1]);
proc_close($process);
return $output;
}
}
4. Metacharacter Filtering:
Filtrelenmesi Gereken Karakterler:
; & | && || ` $ ( ) { } [ ] < > * ? ~ ! # \ " ' space tab newline
function filterMetachars($input) {
$dangerous = [';', '&', '|', '`', ', '(', ')', '<', '>'];
foreach ($dangerous as $char) {
if (strpos($input, $char) !== false) {
throw new Exception('Dangerous character detected');
}
}
return $input;
}
5. Runtime Protection:
Additional Security Measures:
- • Principle of Least Privilege: Minimum yetkilerle çalıştırma
- • Sandboxing: chroot, containers, VMs
- • Resource Limits: CPU, memory, execution time
- • Command Whitelisting: Sadece izin verilen komutlar
- • Logging: Tüm komut executions kayıt altında
Yapmayın:
• Blacklist-based filtering (bypassa açık)
• Simple escaping functions (güvenilmez)
• User input'u directly shell'e geçirme
• Root privileges ile command execution