Code Injection or Remote Code Execution (RCE) enables the attacker to execute malicious code as a result of an injection attack. Code Injection attacks are different than Command Injection attacks. Attacker capabilities depend on the limits of the server-side interpreter (for example, PHP, Python, and more). In some cases, an attacker may be able to escalate from Code Injection to Command Injection.
Typically, Code Injection occurs when an application evaluates code without validating it first. The following is a source code of an example PHP application with a Code Injection bug.
/** * Get the code from a GET input * Example - http://example.com/?code=phpinfo(); */ $code = $_GET['code']; /** * Unsafely evaluate the code * Example - phpinfo(); */ eval("$code;");
Base on the above example, an attacker could use the following construct to execute arbitrary PHP code. As a result, the PHP info page would be displayed.
OS Command Execution
An attacker may be able to escalate a Code Injection vulnerability even further by executing arbitrary operating system commands on the server. Based on the example above, the attacker can execute the
whoami shell command using the
system() function in PHP.
Once an attacker is able to execute OS commands, they could attempt to use a web shell or install other malware. From there, an attacker may even attempt to compromise other internal systems.
Finding and Preventing Code Injection Vulnerabilities
Fortunately, it’s easy to test if your website or web application is vulnerable to code injection and other vulnerabilities by running an automated web scan using the Acunetix vulnerability scanner. Take a demo and find out more about running scans against your website or web application.
If you find Code Injection vulnerabilities, the most effective method to eliminate them is to avoid code evaluation at all costs unless absolutely and explicitly necessary (i.e. you cannot achieve the same result without code evaluation). Generally, evaluating code that contains user input is a dangerous way and you almost always get in trouble. There is even a common mantra for the PHP eval function: “eval() is evil”. If code evaluation is necessary, you must use strong user input validation. It requires as many restrictions for untrusted data as possible. Remember that attackers may use many methods to go around input validation conditions.