What Is Code Injection?
Remote code execution is a serious problem, but what is it exactly and what can be done to avoid it? Read on for details.
Join the DZone community and get the full member experience.Join For Free
Code Injection, or Remote Code Execution (RCE) refers to an attack wherein 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 evaluations containing user input are almost always bound to get you into trouble, hence the common mantra “eval() is evil.”
The following is an example of PHP that is vulnerable to Code Injection.
$code = $_GET['code']; 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 for 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.
Published at DZone with permission of Ian Muscat, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.