Pages

Showing posts with label meterpreter. Show all posts
Showing posts with label meterpreter. Show all posts

Tuesday, May 23, 2017

Post-exploitation: Mounting vmdk files from Meterpreter

Whenever I get a shell on a Windows system with VMware installed I feel a certain frustration at not being able to access the filesystem of the available virtual machines. Although it would be possible to download the .vmdk files to my host and mount them locally this solution is very noisy and heavy due to their high size. The ideal solution would be the one where you could mount the corresponding vmdk files on the “victim's system” using the own resources offered by the VMware installation.

This made me remember the malware developed by Hacking Team, dubbed as Crisis or DaVinci. You can find a nice analysis here. One of the post-exploitation techniques used by DaVinci is the possibility to mount .vmdk files by making use of the driver vstor2 provided by some versions of VMware.  Since the source code was leaked I decided to keep an eye on it to see how they implemented that functionality. You can find that code in the HM_PDAAgent.h file.

However, the way in which they do this functionality is quite limited and not very clear. Look, for example, the following code.



Friday, April 8, 2016

Pazuzu: reflective DLL to run binaries from memory

Most of the times I use Meterpreter in my pentest but sometimes I missed the possibility to run my own binaries from memory to carry out very specific tasks. In this type of scenario I needed a way to run a binary (a simple C application) on the victim host making as little noise as possible (so payloads like download_exe were not an option). To get this I wrote a tiny tool called Pazuzu I would like to share (currently an alpha release with ugly code; no types or macros, etc).

Pazuzu is a Python script that allows you to embed a binary within a precompiled DLL which uses reflective DLL injection. The goal is that you can run your own binary directly from memory.

To run the payload,  you just have to choose the stager you like (reverse TCP, HTTP, HTTPS, etc.) and set the DLL generated by Pazuzu. Pazuzu will execute the binary within the address space of the vulnerable process as long as it has the .reloc section.


Wednesday, November 12, 2014

Metasploit: Getting outbound filtering rules by tracerouting

Deciding between a bind or reverse shell depends greatly on the network environment in which we find ourselves. For example, in the case of choosing a bind shell we have to know in advance if your machine is reachable on any port from outside. Some time ago I wrote how we can get this information (inbound filtering rules) using the packetrecorder script from Meterpreter. Another alternative is to use a IPV6 bind shell (bind_ipv6_tcp). The idea of this payload is to create an IPv6 tunnel over IPv4 with Teredo-relay through which it will make the bind shell achievable from an IPv6 address. You can read more info about this in the post: Revenge of the bind shell. 

On the other hand, in the case of using a reverse shell, we must know the outbound filtering rules of the organization to see if our shell can go outside. In most situations, we usually choose 80 or 443 ports since these ports are rarely blocked for an ordinary user. However, there are cases in which we have a much more restrictive scenario. For example, if we get access to a server from an internal network and want to install a reverse shell from that server to the outside, maybe outgoing connections on ports 80 and 443 are denied. The reverse_tcp_allports() payload was created to work in such environments. This payload will attempt to connect to our handler (installed on certain external machine) using multiple ports. The payload supports the argument LPORT by which we specify the initial connection port. If It can not connect to the handler it will increase the port number 1 by 1 until a connection is done. The problem with this approach is that it is very slow due to timeouts of blocked connections. In addition, much noise is generated as a result of each of these connections.

Friday, January 3, 2014

Loading a kernel driver from Meterpreter

Since life in kernel space is more stealthy, you may want to load your own rootkit kernel driver to hide your shell, some process or connection, etc. and thus make your post-exploitation work more covertly. Not only rootkits but other kind of drivers could be really useful for a pentester. For example, we can load the packet capture driver (npf.sys) from Winpcap if we have the intention to sniff or inject packets into the network to carry out further attacks.

A good and confortable way to load drivers is by using the Service Control Manager API interface which allows you to run and load a kernel driver in a safe way through functions such as CreateServiceA, OpenSCManagerA and OpenServiceA. Taking advantage of Services mixin I made a simple module to achieve this from Meterpreter. Let's see an example with the well-known FU rootkit driver.

[*] Backgrounding session 1...
msf exploit(handler) > use post/windows/manage/driver_loader 
msf post(driver_loader) > set driver_name FU_RK
driver_name => FU_RK
msf post(driver_loader) > set driver_path c:\\windows\\system32\\drivers\\fu.sys
driver_path =>c:\windows\system32\drivers\fu.sys
msf post(driver_loader) > set session 1
session => 1
msf post(driver_loader) > show options

Thursday, December 12, 2013

Metasploit: Controlling Internet Explorer user traffic through a proxy PAC file

We have several alternatives from our shell if we want to play with the DNS to control the victim traffic. A common method is to modify the file C:\WINDOWS\system32\drivers\etc\hosts to add fake entries. From Meterpreter, we can use the module inject_host.rb to facilitate this task. Another option would be to modify the host's DNS to point to our fakedns service with something like: 

C:\Windows\system32>netsh interface ip show interfaces
Índ     Mét         MTU         Estado              Nombre
---  ----------  ----------  ------------  ---------------------------
  1          50  4294967295  connected     Loopback Pseudo-Interface 1
 11          10        1500  connected     Conexión de área local

C:\Windows\system32>netsh interface ip set dns "Conexión de área local" static 192.168.1.200
C:\Windows\system32>ipconfig /all | findstr 192.168.1.200
   Servidores DNS. . . . . . . . . . . . . . : 192.168.1.200

or better yet, we can try to modify the DNS of the router itself if we have access to it (something similar to what Zlob trojan did). This would be great if the host gets its network configuration via DHCP.

These solutions have, however, some drawbacks in certain environments. For example, some AV would raise alerts if it detects suspicious changes in the host file. On the other hand, by changing the host's DNS may have no effect if the firewall/router blocks DNS requests from computers other than the internal DNS servers (as long as our fake DNS server is external).

Friday, July 19, 2013

Metasploit: Getting Ingress firewall rules

This week Rapid7 announced the addition of Metamodules in Metasploit Pro v4.7. One of these modules, "Egress Firewall Testing", allows you to deduce outbound filtering rules from firewalls/routers. No doubt this functionality is really useful for example if we want to leave a reverse shell pointing to our machine. To get this, the metamodule "contacts to Rapid7-hosted server to test open ports and delivers the results in one easy report". 

This module reminds me a little trick I usually do to get just the opposite, that is, to infer ingress firewall rules. In fact, this post could be the second part of the recent "Donde dejo mi bind shell" (spanish) but this time, with the advantage of Metasploit.

Wednesday, June 19, 2013

Metasploit: Man in the Middle through PPTP tunnel

Recently I made a small post-exploitation module to take advantage of the rasdial Windows client. The idea is to create an outbound VPN connection (pptp) from the "victim" machine to a VPN server configured in the "attacker" machine. Once the  pptp tunnel is created we can forward all victim traffic through the tunnel getting a man-in-the-middle attack. 

To get this we have to create a temporal .pbk (phonebook file) with certain parameters and force the rasdial client to use that file. The most important parameter to get the MITM is IpPrioritizeRemote. This option allows rasdial to set a new default route pointing to the new VPN peer IP of the attacker host. This new default GW will have a better metric to the default one so this way we will get that all outbound traffic to internet or to an unknown network will go through our machine. Obviously we need to configure forwarding and masquerading to get a real MITM, which can be easily done with IPTABLES. To make the tests I have used the pptpd package as VPN server from Debian.  The simplest configuration is:

Thursday, June 6, 2013

¿Dónde dejo mi bind shell?


Realizando auditorías internas me he encontrado diversas ocasiones en la que consigo shell en equipos supuestamente localizados dentro de la DMZ de la organización pero de los que desconozco su exposición al exterior. Digo supuestamente, ya que, algunas de estas auditorías tienen un enfoque black-box y por tanto desconozco al completo la topología de la red así como los dispositivos y reglas de networking configuradas en la misma. Si el número de VLANs y subredes es elevado, no es trivial conocer si las máquinas comprometidas tienen acceso desde el exterior.

A veces los servicios y conexiones de la máquina (netstat -anput), ficheros de log, etc. ofrecen pistas sobre la exposición de esa máquina hacia afuera. Así, por ejemplo, si la máquina tiene un Apache corriendo en el puerto 80 y el mismo aloja la Web de la organización se deduce que la misma es alcanzable desde el exterior (algo que podemos corroborar mirando sus logs y conexiones) y que es altamente probable que dicha VLAN tenga otras máquinas con servicios públicos. Sin embargo, en otras ocasiones no es tan claro conocer este hecho. Incluso en el caso del servidor Web lo único que sabemos es que el puerto 80 está expuesto, pero, ¿y el resto de servicios?

Wednesday, May 1, 2013

Metasploit Forensics: Recovery deleted files (NTFS)

The possibilities offered by Meterpreter when developing post-exploitation modules are practically limitless. See for example the modules Imager.rb and NBDServer.rb developed by R. Wesley McGrew and presented at Defcon 19 under the title "Covert Post-Exploitation Forensics With Metasploit".

Such modules allow you to make a copy of physical volumes and logical drives on the compromised computer through the network; or mount the file system of those units on the attacker's computer as if they were another device. Not to mention the possibilities from the forensic standpoint that offer this kind of modules.

Much of this flexibility to carry all kind of tasks from a Meterpreter shell is offered by Railgun. This extension allows us to load Windows libraries in runtime and make use of its functions to have full access to the entire Windows API.

Wednesday, December 5, 2012

Rcapd start Meterpreter module

Durante la fase de post-explotación en una intrusión, tras conseguir una shell en un equipo, uno de los pasos para seguir ganando acceso a otras máquinas o dispositivos de networking es capturar tráfico. Simplemente escuchando el tráfico que pasa por dicha máquina, aunque la misma se encuentre en un entorno conmutado, puede darnos información muy útil sobre la topología de red en la que se encuentra o las posibles vulnerabilidades que podremos explotar más adelante: nombres netbios, users/passwords en claro, paquetes ARP, CDP, DHCP, HSRP, VRRP, etc.

Para capturar tráfico desde una shell, sin embargo, tendremos que hacer uso de herramientas externas que deberemos descargar y ejecutar en el equipo comprometido. Una buena elección es rawcap la cual permite capturar paquetes sin apoyarse en drivers de captura como WinPcap (librería libpcap para Windows utilizada por multitud de herramientas de análisis de tráfico).

Monday, May 21, 2012

Uso eficiente de Metasploit: resource scripts

Cuando empecé a utilizar Metasploit —hace ya unos cuantos años— era bastante caótico para mi auditar una red en busca de vulnerabilidades o información relevante. No seguía una metodología determinada para llevar a cabo las fases de discovering, reconnaissance, exploitation, etc., si no que me dejaba llevar un poco por la intuición. A la larga, esto significa pérdida de tiempo y muchas veces grandes dolores de cabeza por haber obviado algún paso, olvidado algún servicio, ignorado cierta información, etc., con la que podría haber encontrado alguna vulnerabilidad mucho antes.

Wednesday, January 4, 2012

Infección de procesos en Linux con Cymothoa

Estos días he estado jugando un poco con Cymothoa. Para quien no lo conozca, esta herramienta te permite inyectar payloads dentro del espacio de direcciones de un proceso, o dicho de otro modo, troyanizar un proceso en Linux. Cymothoa está desarrollada en C y se encuentra disponible en Backtrack 5 dentro de /pentest/backdoors/cymothoa.

Al no encontrar mucha información sobre su funcionamiento estuve indagando un poco sobre el código para ver exactamente como trabaja. La idea de esta herramienta es sobrescribir directamente el base address de alguna de las librerías utilizadas por el proceso, siendo por defecto el “dynamic linker/loader” (/libr/ld*.so). Los payloads utilizados por Cymothoa están embebidos en el propio binario y pueden verse con el parámetro -S aunque, como veremos a continuación, podremos incorporar los nuestros sin mucho esfuerzo.

Wednesday, June 1, 2011

DNS Port Forwarding con Meterpreter


A diferencia de la versión Pro de Metasploit, una de las limitaciones a la hora de “pivotar” conexiones desde Meterpreter por medio de route es el tipo de herramientas que podemos usar a través del pívot. Esto es debido a que cualquier herramienta que use raw sockets no funcionará a través del túnel, estando limitados a conexiones TCP y UDP que realicen una “conexión completa” (connected sockets).

En el caso de Nmap, por ejemplo, implica que únicamente podemos realizar escaneos de tipo TCP connect (-sT) por medio de socks4 y proxychains, pero será inútil utilizar switches como -sS (syn scan), -O (OS detection) o similares. Aunque otra opción es utilizar port forwarding (portfwd) mediante el cual mapear puertos locales con los de la víctima, estamos limitados a conexiones TCP, por lo que esto también reduce opciones a la hora de elegir herramientas que empleen UDP.