OS Command Injection


 * 1) REDIRECT Command Injection

Description
An OS command injection attack occurs when an attacker attempts to execute system level commands through a vulnerable application. Applications are considered vulnerable to the OS command injection attack if they utilize user input in a system level command.

Examples
The following trivial code snippets are vulnerable to OS command injection on the Unix/Linux platform:


 * C:

int main(int argc, char **argv) {     char command[256]; if(argc != 2) { printf("Error: Please enter a program to time!\n"); return -1; }     memset(&command, 0, sizeof(command)); strcat(command, "time ./"); strcat(command, argv[1]); system(command); return 0; }
 * 1) include 
 * 2) include 
 * 3) include 


 * If this were a suid binary, consider the case when an attacker enters the following: 'ls; cat /etc/shadow'. In the Unix environment, shell commands are separated by a semi-colon. We now can execute system commands at will!


 * Java:

'''There are many sites that will tell you that Java's Runtime.exec is exactly the same as C's system function. This is not true. Both allow you to invoke a new program/process. However, C's system function passes its arguments to the shell (/bin/sh) to be parsed, whereas Runtime.exec tries to split the string into an array of words, then executes the first word in the array with the rest of the words as parameters. Runtime.exec does NOT try to invoke the shell at any point. The key difference is that much of the functionality provided by the shell that could be used for mischief (chaining commands using "&", "&&", "|", "||", etc, redirecting input and output) would simply end up as a parameter being passed to the first command, and likely causing a syntax error, or being thrown out as an invalid parameter.'''

Related Countermeasures
Ideally, a developer should use existing API for their language. For example (Java): Rather than use Runtime.exec to issue a 'mail' command, use the available Java API located at javax.mail.*

If no such available API exists, the developer should scrub all input for malicious characters. Implementing a positive security model would be most efficient. Typically, it is much easier to define the legal characters than the illegal characters.