This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org

Difference between revisions of "Command Injection"

From OWASP
Jump to: navigation, search
(Without the quotes, the shell command line interpretter handles the second command.)
Line 1: Line 1:
{{Template:Attack}}
+
==Description==
  
==Abstract==
+
Purpose of the command injection attack is to inject and execute commands specified by the attacker in the vulnerable application. In situation like this, application which executes unwanted system commands is like a pseudo system shell and the atacker may use it as any authorized system user. However commands are executed with the same privileges and environment as the application has. Command injection attacks are possible in most cases because of lack of correct input data validation, whose in addition can be manipulated by the attacker (forms, cookies, HTTP headers etc.).
  
Executing commands that include unvalidated user input can cause an application to act on behalf of an attacker.
+
There is also different variant of the injection attack called "code injection".
 +
The difference in code injection is that the attacker adds his own code to the existing one. The attacker extends this way the default functionality of the application without necessity of executing system commands. Injected code is executed with the same privileges and environment as application has.
  
==Overview==
 
 
Command injection problems are a subset of injection problem, in which the process is tricked into calling external processes of the attackers choice through the injection of control-plane data into the data plane.
 
 
Command injection attacks take two forms:
 
 
* An attacker can change the command that the program executes: the attacker explicitly controls what the command is.
 
* An attacker can change the environment in which the command executes: the attacker implicitly controls what the command means.
 
 
In this case we are primarily concerned with the first scenario, in which an attacker explicitly controls the command that is executed. Command injection vulnerabilities of this type occur when:
 
 
# Data enters the application from an untrusted source.
 
# The data is part of a string that is executed as a command by the application.
 
# By executing the command, the application gives an attacker a privilege or capability that the attacker would not otherwise have.
 
 
==Consequences ==
 
 
* Access control: Command injection allows for the execution of arbitrary commands and code by the attacker.
 
 
==Exposure period ==
 
 
* Design: It may be possible to find alternate methods for satisfying functional requirements than calling external processes. This is minimal.
 
 
* Implementation: Exposure for this issue is limited almost exclusively to implementation time. Any language or platform is subject to this flaw.
 
 
==Platform ==
 
 
* Language: Any
 
 
* Platform: Any
 
 
==Required resources ==
 
 
Any
 
 
==Severity ==
 
 
High
 
 
==Likelihood  of exploit ==
 
 
Very High
 
 
==Avoidance and mitigation ==
 
 
* Design: If at all possible, use library calls rather than external processes to recreate the desired functionality
 
 
* Implementation: Ensure that all external commands called from the program are statically created, or - if they must take input from a user - that the input and final line generated are vigorously white-list checked.
 
 
* Run time: Run time policy enforcement may be used in a white-list fashion to prevent use of any non-sanctioned commands.
 
 
==Discussion ==
 
 
Command injection is a common problem with wrapper programs. Often, parts of the command to be run are controllable by the end user. If a malicious user injects a character (such as a semi-colon) that delimits the end of one command and the beginning of another, he may then be able to insert an entirely new and unrelated command to do whatever he pleases.
 
 
The most effective way to deter such an attack is to ensure that the input provided by the user adheres to strict rules as to what characters are acceptable. As always, white-list style checking is far preferable to black-list style checking.
 
  
 
==Examples ==
 
==Examples ==
  
===Example 1===
+
Example 1
  
The following code is wrapper around the UNIX command ''cat'' which prints the contents of a file to standard out. It is also injectable:
+
The following code is wrapper around the UNIX command cat which prints the contents of a file to standard out. It is also injectable:
  
 
<pre>
 
<pre>
 +
 
#include <stdio.h>
 
#include <stdio.h>
 
#include <unistd.h>
 
#include <unistd.h>
  
int main(int argc, char **argv) {  
+
int main(int argc, char **argv) {
  char cat[] = "cat ";  
+
char cat[] = "cat ";
  char *command;  
+
char *command;
  size_t commandLength;  
+
size_t commandLength;
  
  commandLength = strlen(cat) + strlen(argv[1]) + 1;  
+
commandLength = strlen(cat) + strlen(argv[1]) + 1;
  command = (char *) malloc(commandLength);  
+
command = (char *) malloc(commandLength);
  strncpy(command, cat, commandLength);  
+
strncpy(command, cat, commandLength);
  strncat(command, argv[1], (commandLength - strlen(cat)) );
+
strncat(command, argv[1], (commandLength - strlen(cat)) );
  
  system(command);  
+
system(command);
  return (0);
+
return (0);
 
}
 
}
 +
 
</pre>
 
</pre>
  
Line 90: Line 37:
  
 
<pre>
 
<pre>
 +
 
$ ./catWrapper Story.txt
 
$ ./catWrapper Story.txt
 
When last we left our heroes...
 
When last we left our heroes...
 +
 
</pre>
 
</pre>
 
 
However, if we add a semicolon and another command to the end of this line, the command is executed by catWrapper with no complaint:
 
However, if we add a semicolon and another command to the end of this line, the command is executed by catWrapper with no complaint:
  
Line 103: Line 51:
 
format.c                strlen.c                useFree*
 
format.c                strlen.c                useFree*
 
catWrapper*            misnull.c              strlength.c                useFree.c              commandinjection.c      nodefault.c            trunc.c                writeWhatWhere.c
 
catWrapper*            misnull.c              strlength.c                useFree.c              commandinjection.c      nodefault.c            trunc.c                writeWhatWhere.c
 +
 
</pre>
 
</pre>
 
 
If catWrapper had been set to have a higher privilege level than the standard user, arbitrary commands could be executed with that higher privilege.
 
If catWrapper had been set to have a higher privilege level than the standard user, arbitrary commands could be executed with that higher privilege.
  
===Example 2===
+
Example 2
  
 
The following simple program accepts a filename as a command line argument and displays the contents of the file back to the user. The program is installed setuid root because it is intended for use as a learning tool to allow system administrators in-training to inspect privileged system files without giving them the ability to modify them or damage the system.
 
The following simple program accepts a filename as a command line argument and displays the contents of the file back to the user. The program is installed setuid root because it is intended for use as a learning tool to allow system administrators in-training to inspect privileged system files without giving them the ability to modify them or damage the system.
  
 
<pre>
 
<pre>
int main(char* argc, char** argv) {
+
      int main(char* argc, char** argv) {
char cmd[CMD_MAX] = "/usr/bin/cat ";
+
              char cmd[CMD_MAX] = "/usr/bin/cat ";
strcat(cmd, argv[1]);
+
              strcat(cmd, argv[1]);
system(cmd);
+
              system(cmd);
}
+
      }
 +
 
 
</pre>
 
</pre>
  
 
Because the program runs with root privileges, the call to system() also executes with root privileges. If a user specifies a standard filename, the call works as expected. However, if an attacker passes a string of the form ";rm -rf /", then the call to system() fails to execute cat due to a lack of arguments and then plows on to recursively delete the contents of the root partition.
 
Because the program runs with root privileges, the call to system() also executes with root privileges. If a user specifies a standard filename, the call works as expected. However, if an attacker passes a string of the form ";rm -rf /", then the call to system() fails to execute cat due to a lack of arguments and then plows on to recursively delete the contents of the root partition.
  
===Example 3===
+
Example 3
  
 
The following code from a privileged program uses the environment variable $APPHOME to determine the application's installation directory and then executes an initialization script in that directory.
 
The following code from a privileged program uses the environment variable $APPHOME to determine the application's installation directory and then executes an initialization script in that directory.
  
 
<pre>
 
<pre>
...
+
      ...
char* home=getenv("APPHOME");
+
      char* home=getenv("APPHOME");
char* cmd=(char*)malloc(strlen(home)+strlen(INITCMD));
+
      char* cmd=(char*)malloc(strlen(home)+strlen(INITCMD));
if (cmd) {  
+
      if (cmd) {
strcpy(cmd,home);
+
              strcpy(cmd,home);
strcat(cmd,INITCMD);
+
              strcat(cmd,INITCMD);
execl(cmd, NULL);
+
              execl(cmd, NULL);
}
+
      }
...
+
      ...
 +
 
 
</pre>
 
</pre>
  
Line 140: Line 90:
  
 
The attacker is using the environment variable to control the command that the program invokes, so the effect of the environment is explicit in this example. We will now turn our attention to what can happen when the attacker can change the way the command is interpreted.
 
The attacker is using the environment variable to control the command that the program invokes, so the effect of the environment is explicit in this example. We will now turn our attention to what can happen when the attacker can change the way the command is interpreted.
 
+
Example 4
===Example 4===
 
  
 
The code below is from a web-based CGI utility that allows users to change their passwords. The password update process under NIS includes running make in the /var/yp directory. Note that since the program updates password records, it has been installed setuid root.
 
The code below is from a web-based CGI utility that allows users to change their passwords. The password update process under NIS includes running make in the /var/yp directory. Note that since the program updates password records, it has been installed setuid root.
  
 
The program invokes make as follows:
 
The program invokes make as follows:
 
 
<pre>
 
<pre>
system("cd /var/yp && make &> /dev/null");
+
      system("cd /var/yp && make &> /dev/null");
 
</pre>
 
</pre>
  
Line 155: Line 103:
 
The environment plays a powerful role in the execution of system commands within programs. Functions like system() and exec() use the environment of the program that calls them, and therefore attackers have a potential opportunity to influence the behavior of these calls.
 
The environment plays a powerful role in the execution of system commands within programs. Functions like system() and exec() use the environment of the program that calls them, and therefore attackers have a potential opportunity to influence the behavior of these calls.
  
==Related problems ==
+
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.
 
 
* [[Injection problem]]
 
  
 
==Related Threats==
 
==Related Threats==
 +
?
  
 
==Related Attacks==
 
==Related Attacks==
  
[[OS Command Injection]]
+
Code Injection
 +
Blind SQL Injection
 +
Blind XPath Injection
 +
LDAP Injection
 +
Relative Path Traversal
 +
Absolute Path Traversal
 +
 
  
 
==Related Vulnerabilities==
 
==Related Vulnerabilities==
 +
 +
  
 
==Related Countermeasures==
 
==Related Countermeasures==
  
* [[:Category:Input Validation]]
+
Category:Input Validation
  
==Categories==
+
Using black and/or white lists which defines valid input data. Such approach is more accurate and provides better risk analysis, when there is need of modification of the lists.
 +
 
 +
E.g. When we expect digits as an input, then we should perform accurate input data validation.
 +
 
 +
<pre>
 +
 
 +
#include <stdio.h>
 +
#include <ctype.h>
 +
#include <string.h>
 +
 
 +
int main(int argc, char **argv)
 +
{
 +
      char a[256];
 +
      strncpy(a, argv[1], sizeof(a)-1);
 +
 
 +
      int b=0;
 +
 
 +
      for(b=0; b<strlen(a); b++) {
 +
              if(isdigit((int)a[b])) printf("%c", a[b]);
 +
      }
 +
 
 +
      printf("\n");
 +
      return 0;
 +
}
 +
</pre>
  
[[Category:Attack]]
+
In PHP for input data validation we may use e.g. preg_match() function:
  
[[Category:Injection Attack]]
 
  
[[Category:OWASP_CLASP_Project]]
+
<pre>
 +
<?php
 +
  $clean = array();
 +
  if (preg_match("/^[0-9]+:[X-Z]+$/D", $_GET['var'])) {
 +
    $clean['var'] = $_GET['var'];
 +
  }
 +
?>
 +
</pre>
  
[[Category:Design]]
+
For special attantion deserves modifier "/D", which additionaly protects against HTTP Response Splitting type of attacks.
  
[[Category:Implementation]]
 
  
[[Category:Input Validation]]
+
Avoid using of environment variables if the attacker may alter their values.
  
[[Category:Code Snippet]]
 
  
[[Category:C]]
+
References:
 +
http://blog.php-security.org/archives/76-Holes-in-most-preg_match-filters.html
 +
 
 +
 
 +
==Categories==
  
{{Template:SecureSoftware}}
+
*[[Category:Injection Attack]]
{{Template:Fortify}}
 

Revision as of 15:19, 4 September 2007

Description

Purpose of the command injection attack is to inject and execute commands specified by the attacker in the vulnerable application. In situation like this, application which executes unwanted system commands is like a pseudo system shell and the atacker may use it as any authorized system user. However commands are executed with the same privileges and environment as the application has. Command injection attacks are possible in most cases because of lack of correct input data validation, whose in addition can be manipulated by the attacker (forms, cookies, HTTP headers etc.).

There is also different variant of the injection attack called "code injection". The difference in code injection is that the attacker adds his own code to the existing one. The attacker extends this way the default functionality of the application without necessity of executing system commands. Injected code is executed with the same privileges and environment as application has.


Examples

Example 1

The following code is wrapper around the UNIX command cat which prints the contents of a file to standard out. It is also injectable:


#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv) {
 char cat[] = "cat ";
 char *command;
 size_t commandLength;

 commandLength = strlen(cat) + strlen(argv[1]) + 1;
 command = (char *) malloc(commandLength);
 strncpy(command, cat, commandLength);
 strncat(command, argv[1], (commandLength - strlen(cat)) );

 system(command);
 return (0);
}

Used normally, the output is simply the contents of the file requested:


$ ./catWrapper Story.txt
When last we left our heroes...

However, if we add a semicolon and another command to the end of this line, the command is executed by catWrapper with no complaint:

$ ./catWrapper "Story.txt; ls"
When last we left our heroes...
Story.txt               doubFree.c              nullpointer.c
unstosig.c              www*                    a.out*
format.c                strlen.c                useFree*
catWrapper*             misnull.c               strlength.c                useFree.c               commandinjection.c      nodefault.c             trunc.c                 writeWhatWhere.c

If catWrapper had been set to have a higher privilege level than the standard user, arbitrary commands could be executed with that higher privilege.

Example 2

The following simple program accepts a filename as a command line argument and displays the contents of the file back to the user. The program is installed setuid root because it is intended for use as a learning tool to allow system administrators in-training to inspect privileged system files without giving them the ability to modify them or damage the system.

       int main(char* argc, char** argv) {
               char cmd[CMD_MAX] = "/usr/bin/cat ";
               strcat(cmd, argv[1]);
               system(cmd);
       }

Because the program runs with root privileges, the call to system() also executes with root privileges. If a user specifies a standard filename, the call works as expected. However, if an attacker passes a string of the form ";rm -rf /", then the call to system() fails to execute cat due to a lack of arguments and then plows on to recursively delete the contents of the root partition.

Example 3

The following code from a privileged program uses the environment variable $APPHOME to determine the application's installation directory and then executes an initialization script in that directory.

       ...
       char* home=getenv("APPHOME");
       char* cmd=(char*)malloc(strlen(home)+strlen(INITCMD));
       if (cmd) {
               strcpy(cmd,home);
               strcat(cmd,INITCMD);
               execl(cmd, NULL);
       }
       ...

As in Example 2, the code in this example allows an attacker to execute arbitrary commands with the elevated privilege of the application. In this example, the attacker can modify the environment variable $APPHOME to specify a different path containing a malicious version of INITCMD. Because the program does not validate the value read from the environment, by controlling the environment variable the attacker can fool the application into running malicious code.

The attacker is using the environment variable to control the command that the program invokes, so the effect of the environment is explicit in this example. We will now turn our attention to what can happen when the attacker can change the way the command is interpreted. Example 4

The code below is from a web-based CGI utility that allows users to change their passwords. The password update process under NIS includes running make in the /var/yp directory. Note that since the program updates password records, it has been installed setuid root.

The program invokes make as follows:

       system("cd /var/yp && make &> /dev/null");

Unlike the previous examples, the command in this example is hardcoded, so an attacker cannot control the argument passed to system(). However, since the program does not specify an absolute path for make and does not scrub any environment variables prior to invoking the command, the attacker can modify their $PATH variable to point to a malicious binary named make and execute the CGI script from a shell prompt. And since the program has been installed setuid root, the attacker's version of make now runs with root privileges.

The environment plays a powerful role in the execution of system commands within programs. Functions like system() and exec() use the environment of the program that calls them, and therefore attackers have a potential opportunity to influence the behavior of these calls.

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 Threats

?

Related Attacks

Code Injection Blind SQL Injection Blind XPath Injection LDAP Injection Relative Path Traversal Absolute Path Traversal


Related Vulnerabilities

Related Countermeasures

Category:Input Validation

Using black and/or white lists which defines valid input data. Such approach is more accurate and provides better risk analysis, when there is need of modification of the lists.

E.g. When we expect digits as an input, then we should perform accurate input data validation.


#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, char **argv)
{
       char a[256];
       strncpy(a, argv[1], sizeof(a)-1);

       int b=0;

       for(b=0; b<strlen(a); b++) {
               if(isdigit((int)a[b])) printf("%c", a[b]);
       }

       printf("\n");
       return 0;
}

In PHP for input data validation we may use e.g. preg_match() function:


<?php
  $clean = array();
  if (preg_match("/^[0-9]+:[X-Z]+$/D", $_GET['var'])) {
     $clean['var'] = $_GET['var'];
  }
?>

For special attantion deserves modifier "/D", which additionaly protects against HTTP Response Splitting type of attacks.


Avoid using of environment variables if the attacker may alter their values.


References: http://blog.php-security.org/archives/76-Holes-in-most-preg_match-filters.html


Categories