GuardAPI Logo
GuardAPI

Fix Command Injection in CodeIgniter

Command Injection in CodeIgniter occurs when an application passes unsanitized user-controlled data to a system shell. This allows an attacker to execute arbitrary OS commands with the privileges of the web server process. To secure this, you must treat every input as hostile and avoid direct shell interaction whenever possible.

The Vulnerable Pattern

public function check_status() {
    $ip = $this->request->getGet('ip');
    // VULNERABLE: Direct concatenation into shell_exec
    $result = shell_exec("ping -c 1 " . $ip);
    return $this->response->setBody($result);
}

The Secure Implementation

The vulnerability exists because shell metacharacters (like ;, &, |) are not filtered, allowing an attacker to append commands (e.g., ?ip=8.8.8.8;cat /etc/passwd). The fix implements two layers of defense: First, 'filter_var' ensures the input strictly conforms to an IP address format, rejecting any payloads containing shell syntax. Second, 'escapeshellarg' adds single quotes around the string and escapes any existing single quotes, ensuring the shell interprets the input as a single literal argument rather than part of the command structure. As a best practice, always prefer built-in PHP functions over system calls.

public function check_status() {
    $ip = $this->request->getGet('ip');
// 1. Strict Input Validation
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    return $this->response->setStatusCode(400)->setBody('Invalid IP address');
}

// 2. Shell Argument Escaping
$safe_ip = escapeshellarg($ip);

// 3. Execution with limited context
$result = shell_exec("ping -c 1 " . $safe_ip);

return $this->response->setBody(htmlspecialchars($result));

}

System Alert • ID: 4747
Target: CodeIgniter API
Potential Vulnerability

Your CodeIgniter API might be exposed to Command Injection

74% of CodeIgniter apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.