www.xmc.pl
5 de mayo de 2022 at 23:10
Very nice post. I just stumbled upon your blog and wished to say that Ive truly enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!
Esta fue mi primera máquina en la plataforma de HackTheBox. Vamos a empezar con un escaneo de nmap con todo, sé que este tipo de barrido hace mucho ruido pero eso no nos importa ahora mismo ya que estamos en la plataforma de prácticas.
Vemos que hay 5 puertos abiertos. Vamos a verlos en detalle. He marcado en amarillo lo interesante como se muestra a continuación:
Aquí se explican los parámetros que pasé en el escaneo de nmap:
Buscaremos primero el puerto ftp, vemos que es un vsftpd con la versión 2.3.4 y que tiene el login anónimo permitido.
Probaremos el acceso para saber si podemos subir algún archivo:
Como podemos ver, no tenemos permisos para subir archivos. Veamos si esta versión es vulnerable a algo:
Si no tiene searchsploit instalado, puede instalarlo como se muestra a continuación:
# sudo git clone https://github.com/offensive-security/exploitdb.git /opt/exploitdb
# sudo ln -sf /opt/exploitdb/searchsploit /usr/local/bin/searchsploit
Extraeremos el exploit ‘Backdoor Command Execution’ ya que no nos interesa el otro y la versión coincidía exactamente con la última. Lo dejaremos para más adelante para comprobar qué hace el exploit y probar la explotación manual del mismo.
Con el escaneo de nmap podemos ver que el puerto SMB está abierto y que está permitiendo la sesión anónima además la versión es SMBv1 ya que el escaneo nos reporta que no se pudo establecer una conexión con SMBv2.
Vamos a probar el inicio de sesión nulo:
El parámetro -L es para el listado, la opción -N inicia la sesión nula y el parámetro –option, añade a la configuración el protocolo SMBv1.
El directorio /tmp tiene un comentario interesante, veamos sobre qué tenemos permisos sin credenciales:
El parámetro -H es para pasar el host a mapear.
Una vez que entramos en el directorio /tmp, buscamos en los directorios ‘orbit-makis’, ‘vmware-root’ y ‘gconfd-makis’ pero tenemos el acceso denegado:
Si buscamos la versión en searchsploit:
Podemos ver que hay un posible script que podría ser útil, por lo que utilizaremos el exploit llamado ‘Username map script execution’.
Si buscamos ‘distccd exploit’ en Google, aparecerán muchos resultados, parece que tiene un CVE (CVE-2004-2687) y que nmap tiene un script NSE para él, así que lo probaremos como se muestra en su ejemplo:
Parece que no tenemos este exploit, así que lo descargaremos desde aquí [ https://svn.nmap.org/nmap/scripts/distcc-cve2004-2687.nse ]. Si no sabes donde se encuentran los scripts de nmap, ejecuta este comando ‘locate «*.nse» ‘ y te mostrará donde se encuentran. En mi caso es ‘/usr/share/nmap/scripts/’. Ahora que tenemos el script de nmap, lo guardaré con el nombre ejecutado anteriormente para que coincidan y lo probaré de nuevo. Lo último antes de volver a ejecutar el comando después de todo esto será actualizar la base de datos de nmap:
¡Y podemos ver que es vulnerable y nos devuelve el comando ejecutado!
Continuaremos con la explotación ahora que tenemos toda la enumeración de los servicios realizada. Seguiremos el mismo orden que antes:
Como al probar el comando ‘GET’ no funcionó, probé con el ‘PUT’ después de buscar y encontrar esto [https://programmerah.com/ftp-use-get-command-550-failed-to-open-file-but-use-the-put-command-to-solve-the-problem-2979/], pero ahora tenemos otro error. He intentado crear un directorio, pero también ha fallado. Parece que no tenemos permisos de escritura.
Después de eso, busqué en el exploit llamado ‘ftp-exploit.rb’ que guardamos antes para buscar qué se estaba explotando y si podía usarlo y esto aparece en la descripción:
Por lo que parece que ya no es válida. El servicio FTP parece un caso fallido.
Vamos a inspeccionar el exploit visto anteriormente.
Y parece que tenemos que usar NTLMv1, nos conseguirá el usuario root o nobody y que sólo tenemos que especificar el valor de la variable ‘username’ en nuestra conexión sustituyendo el payload por nuestro reverse shell teniendo un listener preparado. Pero después de todo tipo de combinaciones la única que funciona teniendo un one liner fue esta:
Los parámetros pasados con netcat eran el -n, que significa numérico solamente, luego tenemos -l que es el modo de escucha, a continuación el -v para verbose y -p para el número de puerto. Podemos pasarlos juntos como lo hacemos o separados.
También veo el script en python de amriunix pero quería hacerlo yo misma, así que busqué por qué no funcionaba pasando el comando ‘nohup’ con el payload en el nombre de usuario, incluso intenté codificar el payload y tampoco funcionó. Parece que una vez que se especifica un nombre de usuario antes de la conexión del socket lo convertirá en una conexión con credenciales, quiero decir que ya no será anónimo. Así que seguí investigando porque con python y ruby esto funciona y es porque ellos crean una conexión de socket antes de enviar las credenciales, así que en resumen, hacían lo mismo que nosotros hacemos aquí.
Como vemos el único servicio que no podía llevarnos a tener privilegios era el servicio DISTCCD, así que vamos a ver la escalada de privilegios como usuario daemon una vez que entramos en la máquina.
Vamos a hacer un reconocimiento para saber si podemos ver los posibles vectores que nos pueden llevar a la escalada de privilegios.
Empezaremos viendo los IDs del usuario daemon así como el listado de comandos permitidos (y prohibidos) para el usuario invocador en el host actual.
Como podemos ver no estamos en ningún grupo interesante ni tenemos privilegios con sudo ya que nos pide una contraseña de usuario que no tenemos.
El siguiente paso será buscar archivos con permisos SUID:
Después de enumerar mucho el sistema, la versión del kernel capta mi interés, ya que es una muy antigua:
El parámetro -a imprime toda la información, en el siguiente orden, nombre del kernel, nombre del nodo de red, versión del kernel, nombre del hardware de la máquina, tipo de procesador, plataforma de hardware y el sistema operativo.
Después de buscar en Google, el primer resultado muestra el exploit ‘Dirty COW’ como se muestra a continuación:
Otra cosa que me pareció curiosa, es que la máquina Lame está basada en Metasploitable2:
Me llamó la atención que nmap tuviera permisos SUID, así que vamos a probar si podemos sacar algo útil:
Dentro del modo interactivo de nmap podríamos generar una shell con !sh para ejecutar comandos.
Como podemos ver, ¡podemos elevar los privilegios con el modo interactivo de nmap!
Vamos por partes, así que buscamos con searchsploit el mismo exploit (EDB-ID) que aparece en Google, en este caso era el segundo:
Otra cosa a tener en cuenta es que la explotación del kernel no es recomendable ya que podemos romper la máquina, pero vamos a intentarlo.
Lo obtenemos y cambiamos el nombre para estar más cómodos:
Si vemos el exploit, en la descripción aparece lo que tenemos que hacer, los pasos a reproducir e incluso el nombre de usuario que podemos cambiar para acceder a la máquina:
Primero pondremos un servidor web en nuestra máquina para enviar el exploit a la víctima, una vez allí seguiremos los pasos de la descripción:
Una vez en la máquina lo compilaremos aquí para que tenga la misma estructura y evadir errores, luego ejecutaremos el binario con la contraseña pasada como parámetro:
El parámetro -pthread es un sinónimo de -pthreads, este añade soporte para multithreading usando la librería POSIX threads. Esta opción establece flags tanto para el preprocesador como para el enlazador. No afecta a la seguridad de los hilos del código objeto producido por el compilador ni a la de las bibliotecas suministradas con él.
La opción -o es para el archivo de salida y -lcrypt significa que el enlazador pide la biblioteca crypt, que debería estar en /lib como libcrypt.so y libcrypt.a. Si no, se encuéntrala en glibc, libc6-dev o similares.
Parece que ha funcionado, así que ahora podemos acceder a través de SSH a la máquina con el nombre de usuario por defecto y la contraseña que hemos establecido:
¡Y entramos con permisos de root! Una vez aquí podemos recuperar las dos banderas de la máquina, la user.txt se encuentra en /home del usuario makis y la otra flag se encuentra en /root.
Hasta la próxima y happy hacking!
Tagged as: fácil / hacking / HTB / Lame / linux / OSCP / pentesting / red team / write-up
This was my first machine on the platform of HackTheBox. We will be starting with a nmap scanning with everything, I know this type of scan makes a lot of noise but we do not care right now about that as we are in the training platform.
We see that there are 5 ports open. We will see them in detail. I marked in yellow the interesting stuff as shown below:
Here are explained the parameters that I passed on the nmap scan:
We will search first for the ftp port, we see that it is a vsftpd with version 2.3.4 and that has the anonymous login allowed.
We will test the access to know if we can upload any files:
As we can see, we do not have permissions to upload files. Let’s see if this version is vulnerable to something:
If you do not have searchsploit installed, you could install it as shown below:
# sudo git clone https://github.com/offensive-security/exploitdb.git /opt/exploitdb
# sudo ln -sf /opt/exploitdb/searchsploit /usr/local/bin/searchsploit
We will retrieve the ‘Backdoor Command Execution‘ exploit as we are not interested in the other and the version matched exactly with the last one. We will save it for later to check what the exploit do and to test the manual exploitation of it.
With the nmap scan we can see that the SMB port is open and that is allowing null session also the version is SMBv1 because the scan report to us that it could not be possible to establish a connection with SMBv2.
Let’s test the null session login:
The -L parameters is for listing, the -N option initiate the null session and the –option one, add the configuration to the protocol SMBv1.
The /tmp directory has a interesting comment, let’s see on what we have permissions whitout credentials:
The -H parameter is to pass the host to map.
Once we enter the /tmp directory, we search on the ‘orbit-makis’, ‘vmware-root’ and ‘gconfd-makis’ directories but we have the access denied:
If we search for the version on searchsploit:
We could see that there is one potential script that could be useful, so we will be using the exploit named ‘Username map script command execution’.
If we search ‘distccd exploit’ on Google, it will appear a lot of results, it seems it has a CVE (CVE-2004-2687) and that nmap has an NSE script for it, so we will test it as shown in their example:
It seems that we do not have this exploit, so we will download it from here [ https://svn.nmap.org/nmap/scripts/distcc-cve2004-2687.nse ]. If you do not know where the scripts of nmap are located, run this command ‘locate «*.nse» ‘ and it will show where there are located. In my case it is ‘/usr/share/nmap/scripts/’. Now that we have the NSE script, I will save it with the name executed before to match the command runned before and test it again. The last thing before running the command again after all this will be update the database of nmap:
And we can see that is vulnerable and it returns the command executed!
We will continue with the exploitation now that we have all the enumeration of the services made. We will follow the same order as before:
As when we try the ‘GET’ command it did not work, I tried with the ‘PUT’ after searching and finding this [https://programmerah.com/ftp-use-get-command-550-failed-to-open-file-but-use-the-put-command-to-solve-the-problem-2979/], but now we have another error. I tried to create a directory, but it failed too. It seems that we do not have permissions to write.
After that, I looked to the exploit called ‘ftp-exploit.rb’ that we saved earlier to search for what was being exploited and if I could use it and this shows in the description:
So it seems that it is not valid anymore. The FTP service seems like a failed case.
We will inspect the exploit seen earlier.
And it seems that we need to use NTLMv1, it will get us root or nobody user and that we only need to specify the value of the variable ‘username’ on our connection replacing the payload with our reverse shell having a listener prepared. But after all types of combinations the only that works having a one liner was this:
The parameters passed with netcat were the -n, that stands for numeric only, then we have -l that is the listen mode, next the -v for verbose and -p for the port number. We could pass them together as we do or separated.
I also see the script in python of amriunix but I wanted to do it myself, so I searched why it did not work passing the ‘nohup’ command with the payload on the username, I even try to encode the payload and it did not work either! It seems that once you specify a username after the socket connection it will convert it to a connection with credentials, I mean that it will not be anonymous/guest anymore. So I continue investigating why with python and ruby this works and is because they create a socket connection before the credentials were sending so in resume, they were doing the same that we do here.
As we see the only service that could not lead us to have privileges was the service DISTCCD, so let’s see the privilege escalation as the user daemon once we enter the machine.
We will be doing a reconnaissance to know if we can see the possible vectors that could lead us to the privilege escalation.
We will start seeing the IDs of the user daemon as well as listing the allowed (and forbidden) commands for the invoking user on the current host.
As we can see we are not in any interesting group neither have privileges with sudo as it prompt for a password of daemon user that we do not have.
The next step will be searching for files with SUID permissions:
After a lot of enumeration of the system, the kernel version catch my interest, as it is a really old one:
The -a parameter print all information, in the following order, kernel name, network node hostname, kernel release, kernel version, machine hardware name, processor type, hardware platform and the operating system.
After searching on Google, the first result shows the exploit ‘Dirty COW’ as shown below:
Another thing that I find that seems funny, is that the machine Lame is based on Metasploitable2:
It caught my attention that nmap has SUID permissions, so let’s test if we can retrieve something useful:
Inside the interactive mode of nmap we could spawn a shell with the command !sh to execute commands.
As we can see, we could elevate privileges with the interactive mode of nmap!
First things first, we search with searchsploit the same exploit (EDB-ID) that shows on Google, in this case was the second one:
Another thing to have in mind is that the kernel exploitation is not recommended as we can broke the machine, but we will try.
We get it and change the name to be more comfortable:
If we see the exploit, on the description it shows what we need to do, the steps to reproduce and even the username that we can change in order to access the machine:
First, we will put a web server on our machine to send the exploit to the victim, once there we will follow the steps on the description:
Once on the machine we will compile it here to have the same structure and evade errors, then we will execute the binary with the password passed as parameter:
The parameter -pthread is a synonym for -pthreads, this add support for multithreading using the POSIX threads library. This option sets flags for both the preprocessor and linker. It does not affect the thread safety of object code produced by the compiler or that of libraries supplied with it.
The -o is for the output file and -lcrypt means the linker asks for crypt library, should be in /lib as libcrypt.so and libcrypt.a. Else find it in glibc, libc6-dev or likewise.
It seems that it worked, so now we could access through SSH to the machine with the default username and the password that we set:
And we are in with root permissions! Once here we could retrieve both flags of the machine.
Till the next one and happy hacking!
Tagged as: easy / hacking / HTB / Lame / linux / OSCP / pentesting / red team / write-up
www.xmc.pl
5 de mayo de 2022 at 23:10
Very nice post. I just stumbled upon your blog and wished to say that Ive truly enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!
wh1tedrvg0n
9 de mayo de 2022 at 12:13
Thank you! I really appreciate this kind of comments 🙂
I will be posting more blog content soon, I’m just given priority to other proyects that I have
Play | Cover | Release Label |
Track Title Track Authors |
Page | Buy | Delete |
---|
Bl4ckse4_
22 de agosto de 2021 at 15:31
This is a good writeup, i’ll try it without yours. i try harder. :)))
otra cosa, ajusta el color del placeholder en los campos para el email, comentario etc etc etc, es que se ven oscuros y como el campo es oscuro, pues apenas se aprecian. es algo constructivo. saludos, /\’bl4ckse4’/\
wh1tedrvg0n
23 de agosto de 2021 at 21:12
¡Muchas gracias! Dale caña :))
PD: Muchas gracias también por el aviso del color de los campos que no se ven bien, ¡enseguida lo cambio!
guccif3r
24 de agosto de 2021 at 04:28
muy buen diseno, me encanta 🙏
wh1tedrvg0n
24 de agosto de 2021 at 18:40
¡Muchas gracias! :))