Code Injection

Description

This is also called Remote Code Execution[RCE]. This attack occurs when the attacker is able to exploit an input validation flaw in a software or a web application and execute malicious code. This can be leveraged to run OS commands in the context of a web application.

This can occur beacause:

How to find the attack Surface?

If any application directly executes or evaluates any user supplied input, without validating it first, is vulnerable to code injection.

How is it any different from OS Command Injection

When we talk about command injection, we talk in terms of extending the default functionality of a application to execute commands(generally in terms of a shell). Code injection on the other hand is restricted by to the functionality provided by a langauage(eg php,python,perl,java,etc).
So, if you are able to expoit the web application using the commands of PHP, you are restricted to the commands that PHP is capable of executing. You can't run Python commands and expect them to run for you.

How does this vulenrability arise?

Lets take an example of PHP Code Injection.

Lets consider a webpage that takes in a query and sends it to the server for evaluation and then returns an output.

http://www.example.com/index.php?name=user1

The code that runs on the server for after the query is submitted is:
<?php eval("echo ".$_REQUEST["name"].s";"); ?>

PHP interpreter evaluates the value passed to the name paramater and then echo's it out.
For example in this case it displays user1 as that was passed a value to the nameparamater in the url

Now coming towards the attack vector.
Since there is no input sanitization performed on the input value and the server is just performing operations on what is being provided to it in the URL,an attacker can leverage it to get to execute malicious commands.

Example: http://www.example.com/index.php?name=user1;phpinfo();
This will cause the php interpreter to echo user1 and then print the compiled information about the php environment.

Further Exploitation

Now that the attacker knows that the web application is vulneranble to code-injection, he can leverage it further to his advantage. Fortunately (for the attacker) PHP allows the execution of OS Commands. The OS commands can be executed by invoking the system(); function.

Example:
http://www.example.com/index.php?name=user1;system('ls');
This echo's user1 followed by printing all the files present in the current directory.

Preventive Measures:

The Following Preventive measures can be taken to prevent Code Injection Attacks.