Code Injection, or Remote Code Execution (RCE) refers to an attack where in an attacker is able to execute malicious code as a result of an injection attack. Code Injection differs from Command Injection since an attacker is confined to the limitations of the language executing the injected code. While it’s possible for an attacker to escalate an attack from Code Injection to execute arbitrary shell commands, it’s not always the case.
Typically, Code Injection occurs when an application evaluates code without validating it first. In general, code evaluation containing user input is almost always bound to get you into trouble, hence the common mantra “eval() is evil”.
The following is an example in PHP that is vulnerable to Code Injection.
/** * Get the code from a GET input * Example - http://example.com/?code=phpinfo(); */ $code = $_GET['code']; /** * Unsafely evaluate the code * Example - phpinfo(); */ eval("\$code;");
In the above example, an attacker could make the following request to execute arbitrary PHP code. In this case, a PHP info page will be displayed.
OS Command Execution
While code injection has the potential to do a lot of damage, an attacker might have the ability to escalate a code injection vulnerability even further by executing arbitrary operating system (OS) commands on the server by using PHP itself to execute shell commands.
The following refers to the above example, but executes the
whoami shell command.
Once an attacker manages to gain OS command execution, the attacker could attempt to gain persistence by using a webshell or install other malware. Form there, an attacker can even attempt to pivot to other internal systems which are not usually exposed publicly.
Preventing Code Injection Vulnerabilities
The most effective method of eliminating Code Injection vulnerabilities is to avoid code evaluation at all costs unless absolutely and explicitly necessary (i.e. there is no possibility of achieving the same result without code evaluation).
In the event where code evaluation is necessary, it is crucial for any user input to be very strongly validated, with as many restrictions as possible on the inputted data.